Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby self and puts

Tags:

ruby

If self is the default receiver in ruby and you call 'puts' in an instance method definition, is an instance of the object the receiver of that call?

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
like image 315
danieltahara Avatar asked Aug 09 '26 12:08

danieltahara


1 Answers

Absolutely, the current object is the receiver of the method call here. The reason why that works is because the Kernel module defines a puts method and is mixed into Object, which is the implicit root class of every Ruby class. Proof:

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 

This prints puts called from #<MyClass:0x00000002399d40>, so the MyClass instance is the receiver.

like image 95
Niklas B. Avatar answered Aug 12 '26 07:08

Niklas B.