---
title: "Ruby的try 方法"
author: "夜鸣猪"
date: "2012-08-02T11:22:48Z"
tags: []
categories: ["编程语言"]
slug: "ruby-try"
draft: false
lastmod: "2012-08-02T11:22:48Z"
id: 1616865
url: "https://hlee.iteye.com/blog/1616865"
---

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:


```ruby
def remove_email(email)                                                                                         
  emails.find_by_email(email).try(:destroy)                                                                     
end  
```

Another example:


```ruby
file_type = file_types.detect { |key,| name.include? key }.try(:last)
```

Lucky little Io has this idea baked in:


```ruby
task ?invoke
```

And, of course, Objective C has something similar.

Here it is in Ruby:


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