Module: Polyfill::V2_6::Hash

Defined in:
lib/polyfill/v2_6/hash.rb

Instance Method Summary collapse

Instance Method Details

#merge(*args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/polyfill/v2_6/hash.rb', line 28

def merge(*args)
  if block_given?
    args.each_with_object(dup) do |arg, h|
      h.merge!(arg, &::Proc.new)
    end
  else
    args.each_with_object(dup) do |arg, h|
      h.merge!(arg)
    end
  end
end

#merge!(*args) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/polyfill/v2_6/hash.rb', line 40

def merge!(*args)
  if block_given?
    args.each_with_object(self) do |arg, h|
      h.merge!(arg, &::Proc.new)
    end
  else
    args.each_with_object(self) do |arg, h|
      h.merge!(arg)
    end
  end
end

#to_hObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/polyfill/v2_6/hash.rb', line 4

def to_h
  return super unless block_given?

  block = ::Proc.new

  pairs = map do |k, v|
    pair = block.call(k, v)

    unless pair.respond_to?(:to_ary)
      raise TypeError, "wrong element type #{pair.class} (expected array)"
    end

    pair = pair.to_ary

    unless pair.length == 2
      raise ArgumentError, "element has wrong array length (expected 2, was #{pair.length})"
    end

    pair
  end

  pairs.to_h
end

#update(*args) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/polyfill/v2_6/hash.rb', line 52

def update(*args)
  if block_given?
    args.each_with_object(self) do |arg, h|
      h.update(arg, &::Proc.new)
    end
  else
    args.each_with_object(self) do |arg, h|
      h.update(arg)
    end
  end
end