[ruby-core:115094] [Ruby master Misc#19931] to_int is not for implicit conversion?
From:
"zverok (Victor Shepelev) via ruby-core" <ruby-core@...>
Date:
2023-10-18 17:48:09 UTC
List:
ruby-core #115094
Issue #19931 has been updated by zverok (Victor Shepelev).
> So basically I thought that #to_i was for explicit conversion and #to_int for implicit conversion; is that not the case?
As far as I understand, it is exactly the case for operations that definitely expect an integer:
```ruby
o = Object.new
def o.to_int = 5
('a'..'z').to_a[o]
#=> "f"
('a'..'z').first(o)
# => ["a", "b", "c", "d", "e"]
'a' * o
# => "aaaaa"
```
(All of those cases would also clearly state "no **implicit** conversion of Object into Integer" if the argument wouldn't have `#to_int`.)
...while number arithmetics seems to be fully defined by `#coerce` and never tries to perform "implicit conversions".
----------------------------------------
Misc #19931: to_int is not for implicit conversion?
https://bugs.ruby-lang.org/issues/19931#change-104998
* Author: Dan0042 (Daniel DeLorme)
* Status: Open
* Priority: Normal
----------------------------------------
While reviewing some implicit vs explicit conversion concepts, I discovered that arithmetic operations do not perform the implicit conversion I expected from #to_int
```ruby
o = Object.new
def o.to_int; 1; end
1 + o #TypeError
```
I understand there's the whole #coerce thing for numbers, but I had expected #to_int to fit neatly into this and cause the object to be implicitly coerced to Integer.
So basically I thought that #to_i was for explicit conversion and #to_int for implicit conversion; is that not the case?
Most of the internet seems to think that (to_int : to_i) relationship is like (to_str : to_s). But I can't seems to find authoritative documentation on the topic.
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- [email protected]
To unsubscribe send an email to [email protected]
ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/