Ruby I and puts
If self is the default receiver in ruby and you call "puts" in the definition of an instance method, is the object instance the receiver of that call?
eg.
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
source to share
Absolutely, the current object is the receiver of the method call here. The reason for this is that a module Kernel
defines a method puts
and is mixed with Object
, which is the implicit root class of every Ruby class. Evidence:
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
Will print puts called from #<MyClass:0x00000002399d40>
, so the instance MyClass
is the recipient.
source to share
MyClass silently inherits from an object that mixes in the core.
The core defines puts as:
$stdout.puts(obj, ...)
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-puts
Hence, you call puts, it moves into itself and cascades down to the core.
source to share