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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With