2012-03-28 61 views
3

如果self是ruby中的默認接收方,並且您在實例方法定義中調用'puts',則該對象的實例是該調用的接收方?紅寶石自己放

E.g.

class MyClass 
     attr_accessor :first_name, :last_name, :size 

     # initialize, etc (name = String, size = int) 

     def full_name 
     fn = first_name + " " + last_name 
     # so here, it is implicitly self.first_name, self.last_name 
     puts fn 
     # what happens here? puts is in the class IO, but myClass 
     # is not in its hierarchy (or is it?) 
     fn 
     end 
    end 

回答

6

絕對,當前對象是方法調用的接收者。之所以這樣做,是因爲Kernel模塊定義了一個puts方法,並混合到Object中,這是每個Ruby類的隱式根類。證明:

class MyClass 
    def foo 
    puts "test" 
    end 
end 

module Kernel 
    # hook `puts` method to trace the receiver 
    alias_method :old_puts, :puts 
    def puts(*args) 
    p "puts called on %s" % self.inspect 
    old_puts(*args) 
    end 
end 

MyClass.new.foo 

這打印puts called from #<MyClass:0x00000002399d40>,因此MyClass實例是接收器。

1

MyClass默默繼承Object,它在Kernel中混合使用。

內核看跌期權的定義是:

$stdout.puts(obj, ...) 

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-puts

因此,你叫看跌期權,它移動到自我,瀑布高達內核。

+0

非常好的一點。這裏有什麼協議,我應該刪除我的答案並留下你的答案(因爲它更準確)? – 2012-03-28 16:17:17

+0

其實我錯了。 'self.puts'不同於在當前類中調用'puts'方法。因此,我的答案的第一個修訂版本基本上與您的說法相同,是對的,您的答案也是如此。 – 2012-03-28 18:05:38