On to_enum and object identity

Good Evening,

I was wondering about the following:

5 == 5.to_i # => true
"Str" == "Str".to_s # => true
enum = (1..3).to_enum
enum == enum.to_enum # => false
enum.object_id == enum.to_enum.object_id # => false

How come Enumerator#to_enum without any arguments doesn't just return self?

Thank you,
Paul

Probably because the contract for the returned instance is broken.
There are methods that are not present in all Enumerable, e.g.

irb(main):009:0> .to_enum.class.public_instance_methods(false).sort
=> [:each, :each_with_index, :each_with_object, :feed, :inspect,
:next, :next_values, :peek, :peek_values, :rewind, :size, :with_index,
:with_object]
irb(main):010:0> Array.instance_method :peek
NameError: undefined method `peek' for class `Array'
        from (irb):10:in `instance_method'
        from (irb):10
        from /usr/bin/irb:11:in `<main>'
irb(main):011:0> Array.instance_method :rewind
NameError: undefined method `rewind' for class `Array'
        from (irb):11:in `instance_method'
        from (irb):11
        from /usr/bin/irb:11:in `<main>'

Kind regards

robert

ยทยทยท

On Thu, Sep 22, 2016 at 4:56 PM, Paul Martensen <paul.martensen@gmx.de> wrote:

I was wondering about the following:

5 == 5.to_i # => true
"Str" == "Str".to_s # => true
enum = (1..3).to_enum
enum == enum.to_enum # => false
enum.object_id == enum.to_enum.object_id # => false

How come Enumerator#to_enum without any arguments doesn't just return self?

--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/