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开发者_C百科_two
elsif method_three
else
puts "none worked"
end
You can use Enumerable#any? as well.
[ :m1, :m2, :m3 ].any?{ |method| object.send( method )} || "None Worked"
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
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
.
精彩评论