Class: String

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

Instance Method Summary collapse

Instance Method Details

#to_hObject



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

def to_h
  if self[0] != "{" || self[-1] != "}"
    raise ArgumentError.new("invalid value for `#{__method__}': '#{self}'")
  end

  begin
    str = self.chomp.gsub(/"|^{|}$/, '')
    arr = str.split(/,[\s]*|=>/)
    arr.each_with_index{|column, idx|
      arr[idx] = column.to_i if column =~ /^\d+$/
    }
    new_style_res = Hash[*arr]

    new_style_res
  rescue
    raise ArgumentError.new("invalid value for `#{__method__}': '#{self}'")
  end
end