Call Me Maybe: Why does is_a return value of the method and Boolean?


#1

Along with doing the lesson I'm testing my code against rubyfiddle.com
I have a few questions:

In the beginning of this track we are told and later reinforced that almost everything in Ruby is an Object, and that methods are called on objects ex:

Define Proc

addoneproc = Proc.new { |x| puts x+=1 }

Calling a method that takes a proc as a parameter on the Array object

[1,2,3].each(&addoneproc)

Define Method. / Are terms 'method' and 'function' interchangeable in Ruby?

def stand_alone 
  puts "No one calls me but ME!"
end

Seems the method is executing on its own... or is it like in Javascript, executing on the global object stand_alone this line of code returns the value of the call to the method (why is it executing?) as well as a Boolean 'True,' which means the method is an Object? please explain.

print stand_alone.is_a? Object    # true

#2

They are synonymous in one sense... They are both functions. In a classless environment such as ES5 (earlier JavaScript), a function is written on the global object, whereas a method is a member written on a class constructor, or its prototype.

Ruby is an object oriented language so everything belongs to a class, hence the use of the term method to refer to a function object.

stand_alone is a method that takes no parameter. The value is implicitly returned in Ruby, which means when there is no return statement, the last line is the return value. However, since the method puts the value, there is no value to return.

def stand_alone 
  "No one calls me but ME!"
end

puts stand_alone     # No one calls me but ME!

In what appears to be a global inline statement. We solve this (or rather prevent it from executing) by leaving it as a value only Now when we refer to the object, the line will be returned, as witnessed above.

Reading that makes more sense...

https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls

https://en.wikipedia.org/wiki/Singleton_pattern

https://www.startpage.com/do/dsearch?query=singleton++Ruby


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.