Harry Forbess
Harry Forbess

Reputation: 2134

How can I make this ruby code throw an exception and bail?

I want this to throw an exception and die:

begin
  if meridian != "AM" and meridian != "PM"
    rescue
    puts MESSAGE
  end
end   

I googled a lot, but nothing seems to work. I want an if statement to throw an exception if it fails.

Am I looking at this the wrong way?

Upvotes: 3

Views: 172

Answers (6)

Harry Forbess
Harry Forbess

Reputation: 2134

this worked

      MESSAGE = "Check your formatting"
      if meridian != "AM" and  meridian  != "PM"
          abort( MESSAGE )
      end  

Upvotes: 0

Zepplock
Zepplock

Reputation: 29175

Either remove begin/rescue/end around your if or replace puts MESSAGE with raise "some_message_here"

Upvotes: 0

agmin
agmin

Reputation: 9378

You don't need a begin/rescue because you aren't encountering any errors with your if statement. Instead:

 raise "message" if meridian != "AM" and meridian != "PM"

Upvotes: 0

yeyo
yeyo

Reputation: 3009

IMHO you should use fail instead of raise, for readability matters and see link below.

fail "message" unless ["AM", "PM"].include? meridian

https://github.com/bbatsov/ruby-style-guide#exceptions

Upvotes: 1

Matheus Moreira
Matheus Moreira

Reputation: 17030

You can also use regular expressions:

raise 'message' unless meridian =~ /\A(a|p)m\z/i

This matches independently of case, and works with symbols too.

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37527

Try this:

raise "message" unless ["AM", "PM"].include? meridian

Upvotes: 4

Related Questions