ribamar
ribamar

Reputation: 1495

Ruby: implementing function returning an Enumerator

For a personal Hash implementation, I would like to create a banged version of map, map!, ie, a version that changes the current object, like the one that exists for Array. When a block is given, the implementation below seems to work correctly:

class MyHash < Hash

  def map! &block
    self.map { |ek, ev| self[ek] = block[ev] }  if block_given?
    # how to return the Enumerator if block not given?
  end

end

When called without a block, the hash.map returns an Enumerator, like in the example below:

h.map
=> #<Enumerator: {1=>2, 12=>21, 6=>3}:map>

What should I add to my function to make it return the Enumerator when a block is not given?

Upvotes: 1

Views: 131

Answers (2)

Max
Max

Reputation: 22325

This is surprisingly easy using Object#to_enum

class MyHash < Hash
  def map!
    if block_given?
      each { |k, v| self[k] = yield v }
    else
      to_enum :map!
    end
  end
end

Upvotes: 2

Giovanni Benussi
Giovanni Benussi

Reputation: 3500

I can't get what your code does, but you can try to return self.each:

def map! &block
    if block_given?
        self.map { |ek, ev| self[ek] = block[ev] }
    else
        self.each
    end
end

Upvotes: -1

Related Questions