# 在 Ruby 如何找到方法的定義？

> 

Published: 2011-08-09
URL: https://kaochenlong.com/how-to-find-a-method-definition-in-ruby

---

剛好昨天有朋友問到，就順便筆記一下。

Ruby 官方文件很多，但有時對入門的朋友來說，常會遇到「我想看看 XX 方法的詳細用法，我該找哪個類別或模組的文件?」的問題。簡單的說，「常翻文件」就是這個問題最好的答案啦，除此之外，你也可以使用 [Object#method](http://www.ruby-doc.org/core/classes/Object.html#M001038) 來找。

例如我想要知道 `puts` 這個很常用的方法是定義在哪邊的：

```ruby
print method(:puts) # &lt;Method: Object(Kernel)#puts&gt;
```

它會回傳一個 Method 類別的實體，並且寫著 `Object(Kernel)#puts`，表示這個 `puts` 方法是被定義在 Object 的(事實上是在 Kernel，透過 Mixin 混到 Object 裡的)

回傳的這個 Method 類別實體其實也可以直接呼叫，例如：

```ruby
my_puts = method(:puts)
my_puts.call(&quot;Hello Ruby&quot;)
```

另外在寫 Rails 的時候，有時候想要知道某個好用的方法或 helper 是放在哪邊，想看看原始碼是怎麼寫的，也可以透過這個方式(Ruby 1.9 限定)：

```ruby
require &#39;active_support/all&#39;
puts 10.day.method(:ago).source_location

# [&quot;/Users/eddie/.rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.0.9/lib/active_support/core_ext/numeric/time.rb&quot;, 63]

```

`Method#source_location` 會回傳一個陣列，裡面放著檔名以及在第幾行。

### 參考資料：

Ruby API – [Method 類別](http://www.ruby-doc.org/core/classes/Method.html)


