Search code examples
rubykeywordrational-numbers

Why is the new method not needed for creating Rational in ruby


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)?


Solution

  • 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