method方法

2016-06-10  本文已影响20人  kamionayuki

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

上一篇 下一篇

猜你喜欢

热点阅读