Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 401
Jeff Storey Avatar asked Jun 27 '12 00:06

Jeff Storey


2 Answers

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

like image 129
Linuxios Avatar answered Sep 25 '22 20:09

Linuxios


It's a method that happens to have the same name as the class. It's a common conversion idiom in Ruby.

like image 31
jmdeldin Avatar answered Sep 22 '22 20:09

jmdeldin