Reputation: 5708
It was my understanding that there weren't any functions per se, but that everything was a method and that anything whose class you don't have to name explicitly is really a method of the Kernel
.
I thought methods are objects because that method gets
has a method chomp
as in myStr = gets.chomp
. Ruby-doc.org tells that chomp
is a String
method. In fact, gets.class
tells that gets
is a String
object. What is going on here? How can a method
be a String
object? From what mechanism does this behavior result, and where can I learn more about it?
Upvotes: 0
Views: 40
Reputation: 168101
You are confusing the environment/receiver of a method call and the return value of a method call. In general, they are not the same. gets
is primarily defined on Kernel
, and its return value is a String
instance. chomp
is defined on String
and its return value is a String
. gets
being defined on IO
is just a secondary thing for convenience.
Upvotes: 2
Reputation: 9639
Actually, gets
is a method call, and returned value is of type String
. The string has method chomp
, so you could nicely chain them as you mentioned:
myStr = gets.chomp
This is the same like:
myStr = gets().chomp()
UPDATE
If you want to obtain a method as an object, try:
chomp = "Hello".method(:chomp)
=> #<Method: String#chomp>
chomp.call # this is how you can "call" the method
Check the documentation for more!
Hope that helps!
Upvotes: 2