How can a class also be a method in Ruby?

Asked

Viewed 80 times

3

See the class Integer:

Integer.class
=> Class

It also seems that it is a method, at the same time that it is a class:

Integer 10.5
=> 10

How is this possible in Ruby? Where is this method defined? What mechanisms does Ruby use to know if I’m calling the method or the class?

1 answer

3


How this is possible in Ruby?

Thus:

class C
  attr_accessor :x
  def initialize(x)
    @x = x
  end
end

# N.B.
def C(x)
  C.new(x)
end

repl it.: https://repl.it/repls/CurvyTerrificRegister.

Where this method is defined?

This is an object method main. The class of this object is Object. This class includes the module Kernel. Method documentation.

What mechanisms does Ruby use to know if I’m calling the method or the class?

Method calls are always the message passing:

  • C.new(42) = send the message new for the object C.

  • C(42) = send the message C for the object main.

(I personally find it confusing. I wouldn’t use that.)

  • Thanks for the answer! Can you supplement it with the other questions in the question? " How is this possible in Ruby? Where is this method defined? What mechanisms does Ruby use to know if I’m calling the method or the class?"

  • @vnbrs Please see the edition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.