Ruby的try 方法_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Ruby的try 方法

Ruby的try 方法

 2012/8/21 11:11:23  夜鸣猪  程序员俱乐部  我要评论(0)
  • 摘要:Thisissomethingwe’reusingonGitHubthatIreallywishIstartedusingsooner.Forlackofabettername,it’scalledtry().Itworkslikethis:defremove_email(email)emails.find_by_email(email).try(:destroy)endAnotherexample:file_type=file_types.detect{|key,|name.include
  • 标签:方法 Ruby
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
发表评论
用户名: 匿名