Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be coerced into an integer in Ruby?

Tags:

ruby

In Ruby, if you try to do 2 + nil, for example, you get

TypeError: nil can't be coerced into Integer

but, this made me wonder if there is anything that can be coerced into an Integer. A lot of times Integers are coerced to other numeric types, like here

(2 + Rational('1/2')).class 
# => Rational
(2 + 0.5).class
# => Float
(2 + 1i).class
# => Complex

And, Booleans in Ruby don't get coerced to Integer. So, what does get coerced into an Integer?

like image 502
Eli Sadoff Avatar asked Feb 05 '23 05:02

Eli Sadoff


1 Answers

In ruby arbitrary classes can choose to be coercible to other types by defining a coerce method. This is described in detail here.

like image 64
lorefnon Avatar answered Feb 16 '23 22:02

lorefnon