Ruby idiom: method call or default

What is the correct way to do this in Ruby?

def callOrElse(obj, method, default)
  if obj.respond_to?(method) 
     obj.__send__(method)
  else 
     default
  end
end
+5
source share
3 answers

Because it was not suggested as an answer:

result = obj.method rescue default

As with @slhck, I probably would not use this if I knew that there was a reasonable chance that obj would not respond to the method, but this is an option.

+3
source

So you want something similar to x = obj.method || default? Ruby is the perfect language for creating your own upstream constructs:

class Object
  def try_method(name, *args, &block)
    self.respond_to?(name) ? self.send(name, *args, &block) : nil     
  end
end

p "Hello".try_method(:downcase) || "default" # "hello"
p "hello".try_method(:not_existing) || "default" # "default"

, ? , Ick maybe - ( ):

p "hello".maybe_has_method.not_existing || "default" # "default"

: , , , , , . nil , , ? Ick : object_or_nil.maybe.method || default

+3

I will probably go for

obj.respond_to?(method) ? obj.__send__(method) : default
+2
source

All Articles