- 定义
Looks up the named method as a receiver in obj, returning aMethod
object (or raisingNameError
). TheMethod
object acts as a closure in obj’s objectinstance, so instance variables and the value ofself
remainavailable.
- 返回值
"33".method(:to_i)
#<Method: String#to_i>
- 一些应用
- 查找方法的定义
"33".method(:to_i).owner
#=>String
"33".method(:to_i).source_location
#=>nil,如果是core lib中的方法,source_location似乎是返回nil(存疑)
class String
def my_f
self * 2
end
end
"33".method(:my_f).owner
#=>String
"33".method(:my_f).source_location
#=>["/your/file/path/filename.rb", 1300],返回定义该方法的文件路径以及行数
require 'csv'
CSV.new('string').method(:flock)
#=> #<Method: CSV#flock>
CSV.new('string').method(:flock).owner
CSV.new('string').method(:flock).source_location
#=> ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180]
- 调用方法本身
m = "33".method(:to_i)
m.call
#=>33
from:
http://stackoverflow.com/questions/175655/how-to-find-where-a-method-is-defined-at-runtime