是不是有時候覺得,幹這方法到底在哪裡?到底是幹嘛的?然後這個object到底有哪些方法可以用?滿頭問好???本人正是如此

今天假設我們有一個 Cat class,裡面有兩個methods,當然可能更多。

1
2
3
4
5
6
7
class Cat
  def run
  end
  
  def eat
  end
end

那我們可以用 Cat.new.methods,在consolo裡面查這個class裡,到底有哪些方法

1
2
Cat.new.methods
 => [:run, :eat, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :method, :public_method, :define_singleton_method, :public_send, :singleton_method, :extend, :pp, :to_enum, :enum_for, :<=>, :===, :=~, :!~, :eql?, :respond_to?, :freeze, :inspect, :object_id, :send, :to_s, :display, :nil?, :hash, :class, :singleton_class, :clone, :itself, :dup, :taint, :yield_self, :untaint, :tainted?, :untrusted?, :untrust, :frozen?, :trust, :methods, :singleton_methods, :protected_methods, :private_methods, :!, :equal?, :instance_eval, :==, :instance_exec, :!=, :__id__, :__send__]

有看到前面兩個method嗎?是我們自己定義的method,也看到了這個calss繼承的所有的method。

那我只想看只定義在這個calss裡的method呢?

可以用 Cat.new.methods - Object.new.methods

1
Cat.new.methods - Object.new.methods

那有些幫你做好的method,它的原始碼在哪裡?想看它是怎麼做的

這時候我們就可以用Rails 的小技巧

1
2
3
4
5
6
7
cat = Cat.new 

cat.method(:run)
# => #<Method: cat#run>

cat.method(:run).source_location
# => ["cat.rb", 1]

這樣追,一直追追追,追到天涯海角吧~~~

https://www.spreered.com/learn-rail-by-ruby/
本篇參考以上文章