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 Integer
s 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
?
In ruby arbitrary classes can choose to be coercible to other types by defining a coerce
method. This is described in detail here.
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