Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/zendesk_apps_tools/array_patch.rb

Instance Method Summary collapse

Instance Method Details

#to_hObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/zendesk_apps_tools/array_patch.rb', line 3

def to_h
  if elem_index = index { |elem| !elem.is_a?(Array) }
    raise TypeError.new("wrong element type #{self[elem_index].class} at #{elem_index} (expected array)")
  end

  each_with_index.inject({}) do |hash, elem|
    pair, index = elem

    if pair.size != 2
      raise ArgumentError.new("wrong array length at #{index} (expected 2, was #{pair.size})")
    end

    hash.tap do |h|
      key, val = pair
      h[key] = val
    end
  end
end