Ruby class is called method
Is there a way to define a class so that you can name that class as a method to execute your desired code? For example (doesn't work):
class MySpecialClass
def self(x)
x*x
end
end
In the console:
MySpecialClass(4)
=> 16
MySpecialClass(5)
=> 25
I can't find anything on this online, however some Ruby classes (2.1.2) seem to have similar behavior, eg. String
:
String("hello")
=> "hello"
String(3)
=> "3"
Note that this is not the same behavior as a class method String#new
:
String.new (3) TypeError: no implicit conversion of Fixnum into String
+3
source to share
1 answer
All you have to do is define a method with the same name as the class:
def MySpecialClass(x)
x * x
end
String(foo)
actually calls the method Kernel#String
.
+9
source to share