2012-03-28 5 views
3

self가 루비의 기본 수신자이고 인스턴스 메소드 정의에서 'puts'를 호출하는 경우 해당 호출의 수신자 인 객체의 인스턴스입니까?Ruby self and puts

예.

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 메소드를 정의하고 모든 Ruby 클래스의 암시 적 루트 클래스 인 Object에 혼합되어 있기 때문입니다. 증명 :

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

아주 좋은 지적입니다. 여기 프로토콜은 무엇입니까, 내 대답을 삭제하고 내버려둬 야합니까 (더 정확한지)? –

+0

사실 나는 틀 렸습니다. 'self.puts'는 현재 클래스에서'puts' 메소드를 호출하는 것과 다릅니다. 그래서 기본적으로 당신 것과 똑같은 대답이었던 제 답변의 첫 번째 수정은 옳았고 당신의 것이 었습니다. –