Method: Weak::Map#to_h

Defined in:
lib/weak/map.rb

#to_h {|key, value| ... } ⇒ Hash

Returns a new ‘Hash` which considers object identity for keys which contains the key-value pairs in `self`.

Yields:

  • (key, value)

    When a block is given, returns a new Hash object whose content is based on the block; the block should return a 2-element Array object specifying the key-value pair to be included in the returned Hash.

Yield Parameters:

  • key (Object)

    the key of the current key-value pair

  • value (Object)

    the value of the current key-value pair

Returns:

  • (Hash)

    a new ‘Hash` which considers object identity for keys which contains the key-value pairs in `self`.

[View source]

653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/weak/map.rb', line 653

def to_h(&block)
  hash = {}.compare_by_identity
  if block_given?
    each do |key, value|
      map = yield(key, value)
      ary = Array.try_convert(map)
      unless ary
        raise TypeError, "wrong element type #{map.class} (expected array)"
      end
      unless ary.size == 2
        raise ArgumentError, "element has wrong array length " \
          "(expected 2, was #{ary.size})"
      end

      hash[ary[0]] = ary[1]
    end
  else
    each do |key, value|
      hash[key] = value
    end
  end

  hash
end