Possible Duplicate:
Ruby syntax question: Rational(a, b) and Rational.new!(a, b)
I'm in the process of reading the ruby pickaxe book, and I'm confused about the syntax of creating rational numbers.
Rational(3,4) * Rational(1,2)
produces
=> 3/8
Why is the new
method not needed for Rational
(I also noticed for example I can create a string without the new method)?
For one thing, Ruby has no new
keyword. new
is a class method that all classes have (they inherit it from Class
) that creates an object of that class. When you see something like Rational(3,4)
, Rational
is really just a private method of Object
(defined in Kernel
) that makes creating rational numbers easier. For more on those constructor-methods, see this answer of mine: https://stackoverflow.com/a/9677125/1008938
It's a method that happens to have the same name as the class. It's a common conversion idiom in Ruby.
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