Search code examples
rubymethodsdefaultidioms

Ruby idiom: method call or else default


What's the proper way of doing this in Ruby?

def callOrElse(obj, method, default)
  if obj.respond_to?(method) 
     obj.__send__(method)
  else 
     default
  end
end

Solution

  • Because it hasn't been offered as an answer:

    result = obj.method rescue default
    

    As with @slhck, I probably wouldn't use this when I knew there was a reasonable chance that obj won't respond to method, but it is an option.