ruby.social is one of the many independent Mastodon servers you can use to participate in the fediverse.
If you are interested in the Ruby programming language, come join us! Tell us about yourself when signing up. If you just want to join Mastodon, another server will be a better place for you.

Administered by:

Server stats:

1.1K
active users

Wait a minute, shouldn't Integer#+ call `to_int` on the other value if it's not an Integer?

```
class FourtyTwo
def to_int
42
end
end

p(2 + FourtyTwo.new)
```
```
test.rb:9:in `+': FourtyTwo can't be coerced into Integer (TypeError)
```

Esparta :ruby:

@postmodern TIL and it's implemented on most of the default classes [0]:

class One
def coerce(other)
[other, 1]
end
def +(other)
other + 1
end
end

p (2 + One.new)
# => 3

p (One.new + 4)
# => 5

Thanks, @mudge

[0] ie. Integer#coerce docs.ruby-lang.org/en/3.2/Inte

docs.ruby-lang.orgclass Integer - Documentation for Ruby 3.2