Oswald Roswell
Oswald Roswell

Reputation: 65

In Ruby, what is "putting" when we command ruby to puts something?

Say we are in the Interactive Ruby Browser and run:

>> sometext = "Hello, Cruel World!"
>> puts sometext
Hello, Cruel World!
=> nil
>>

What object is doing the putting? I am sure that having a naked method sitting there seeming to "puts" itself is "syntactic sugar," but I also bet that there is some explicit name for the "object" that is performing these actions... something like Ruby::Self or Self::Thing or... what is it?

Upvotes: 0

Views: 134

Answers (3)

Marek Fajkus
Marek Fajkus

Reputation: 588

Puts is implemented in Ruby's kernel. More specifically the IO class where this came from. You can find more about this in documentation: http://ruby-doc.org/core-2.2.2/IO.html#method-i-puts

Upvotes: 2

Keith Bennett
Keith Bennett

Reputation: 4950

To illustrate in irb:

2.3.0 :002 > Kernel.private_instance_methods.include?(:puts)
 => true
2.3.0 :003 > self
 => main
2.3.0 :004 > self.class
 => Object
2.3.0 :005 > self.class.ancestors
 => [Object, Kernel, BasicObject]

As Kenrick Chien said in his comment below, "Kernel is a module mixed in to Object, and it provides a private method called puts. In Ruby, private methods can not be called with an explicit receiver. So when you are asking about what object is doing the putting, it's the current object in scope (self) when you call puts."

Upvotes: 4

sawa
sawa

Reputation: 168081

It is a special object called main, which is an instance of Object, which inherits Kernel.

Upvotes: 3

Related Questions