Reputation: 5990
Like in title - for example I have a method DrawMe(what)
and I want to allow to run this method when what
argument is equal to one of this values: {"house", "garden", "cat", "dog"}
- and if not then this method should be stopped and an error should be printed. Any ideas?
Upvotes: 1
Views: 441
Reputation: 303261
class Draw
ALLOWED = %w[house garden cat dog]
def self.me(what)
raise ArgumentError, "Unknown drawable '#{what}'" unless ALLOWED.include?(what)
# Otherwise, carry on!
puts "I'm going to draw a #{what}!"
end
end
Draw.me('garden') #=> I'm going to draw a garden!
Draw.me('cat' ) #=> I'm going to draw a cat!
Draw.me('morals') #=> RuntimeError: Unknown drawable 'morals'
However, note that most of the time you should not be ensuring that developers passed the right type of value into your method. Your method will raise its own error if something explodes as a result of misuse; it's a waste of your time and the computer's time to attempt to check and catch errors like this.
Edit: If you need to use this frequently, you could monkeypatch it in everywhere:
class Object
def ensure_in( enumerable )
unless enumerable.include?( self )
raise ArgumentError, "#{self} must be one of #{enumerable}"
end
end
end
def me(what)
what.ensure_in( ALLOWED )
# Go ahead
end
Upvotes: 5