Ruby的try 方法

This is something we’re using on GitHub that I really wish I started using sooner. For lack of a better name, it’s called try().

It works like this:

def remove_email(email)                                                                                         
  emails.find_by_email(email).try(:destroy)                                                                     
end  

Another example:

file_type = file_types.detect { |key,| name.include? key }.try(:last)

Lucky little Io has this idea baked in:

task ?invoke

And, of course, Objective C has something similar.

Here it is in Ruby:

class Object
  ##
  #   @person ? @person.name : nil
  # vs
  #   @person.try(:name)
  def try(method)
    send method if respond_to? method
  end
end

Enjoy

你可能感兴趣的:(github,Ruby,try)