Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save tlux/f28ddaee391a9b9148c3 to your computer and use it in GitHub Desktop.

Select an option

Save tlux/f28ddaee391a9b9148c3 to your computer and use it in GitHub Desktop.
Object#try_first returns the result of the first responding method specified in an Array
# Usage:
#
# object = MyObject.new
# object.label = "Some content here..."
#
# object.try_first([:name, :label, :caption]) # => "Some content here..."
# object.try_first(:description) # => nil
class Object
def try_first(method_names, *args, &block)
method_name = Array(method_names).find { |method_name| respond_to?(method_name) }
public_send(method_name, *args, &block) if method_name
end
def try_last(method_names, *args, &block)
try_first(method_names.reverse, *args, &block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment