Reputation: 19863
Is there a pretty way to make a series of method calls in ruby UNTIL one returns true?
This was my first thought, but was thinking there might be a nicer way:
if method_one
elsif method_two
elsif method_three
else
puts "none worked"
end
Upvotes: 3
Views: 778
Reputation: 2381
You can use Enumerable#any? as well.
[ :m1, :m2, :m3 ].any?{ |method| object.send( method )} || "None Worked"
Upvotes: 6
Reputation: 64363
Try this:
[:m1, :m2, :m3, ...].find{ |m| send(m) } != nil || "none worked"
Returns true
if one of the methods returns true
otherwise returns none worked
.
Upvotes: 4
Reputation: 24108
There are number of Ruby-ish options. One interesting is:
method_one || method_two || method_three || Proc.new { puts "none worked" }.call
or
method_one || method_two || method_three || lambda { puts "none worked" }.call
Upvotes: 5