Reputation: 2134
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
Reputation: 2134
this worked
MESSAGE = "Check your formatting"
if meridian != "AM" and meridian != "PM"
abort( MESSAGE )
end
Upvotes: 0
Reputation: 29175
Either remove begin
/rescue
/end
around your if
or replace puts MESSAGE
with raise "some_message_here"
Upvotes: 0
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
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
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
Reputation: 37527
Try this:
raise "message" unless ["AM", "PM"].include? meridian
Upvotes: 4