How can a class also be a method in Ruby?

3

See class Integer :

Integer.class
=> Class

It also seems like it's a method, at the same time it's 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?

    
asked by anonymous 18.11.2018 / 14:14

1 answer

3
  

How is this possible in Ruby?

So:

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

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

repl.it: link .

  

Where is this method defined?

This is a method of object 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 message passing:

  • C.new(42) = send message new to object C .

  • C(42) = send message C to object main .

(I personally find this confusing. I would not use this.)

    
20.11.2018 / 18:35