Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class called as a method

Tags:

ruby

Is there a way to define a class such that you can call that class as a method to execute desired code? For example (doesn't work):

class MySpecialClass
  def self(x)
    x*x
  end
end

In a console:

MySpecialClass(4)
=> 16
MySpecialClass(5)
=> 25

I can't seem to find anything on this online, however some Ruby (2.1.2) classes seem capable of similar behavior, e.g. String:

String("hello")
=> "hello"
String(3)
=> "3"

Note that this is not the same behavior as the String#new class method:

String.new(3)
TypeError: no implicit conversion of Fixnum into String
like image 748
eirikir Avatar asked May 01 '26 08:05

eirikir


1 Answers

All you have to do is define a method with the same name as the class:

def MySpecialClass(x)
  x * x
end

String(foo) is actually calling the Kernel#String method.

like image 126
August Avatar answered May 03 '26 05:05

August