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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With