eddie tuell
eddie tuell

Reputation: 165

convert hash key to an integer in ruby

I have a initialized a hash from a txt file. If I am not mistaken, the key is currently a string. How can I make it an integer? Any help would be greatly appreciated.

Code:

products_file = File.open("files.txt")
products = {}
while !products_file.eof?
  x, *products[x] = products_file.gets.chomp.split(",")
  a = products[x]
  a[0].strip!
  a[1] = a[1].strip.to_f
end
puts products

File:

199, Shoes, 59.99
211, Shirts, 19.99
245, Hats, 25.99
689, Coats, 99.99
712, Beanies, 6.99

My result is:

{"199"=>["Shoes", 59.99], "211"=>["Shirts", 19.99], "245"=>["Hats", 25.99], "689"=>["Coats", 99.99], "712"=>["Beanies", 6.99]}

Upvotes: 0

Views: 5599

Answers (2)

onyxrev
onyxrev

Reputation: 649

I'd do Hash[ hash.keys.map(&:to_i).zip(hash.values) ]

Upvotes: 3

Brandan
Brandan

Reputation: 14983

You can use inject to build a new hash with integer keys:

hash = {"199"=>["Shoes", 59.99], "211"=>["Shirts", 19.99]}

p hash.inject({}) { |memo, item| memo[Integer(item[0])] = item[1]; memo }
  # => {199=>["Shoes", 59.99], 211=>["Shirts", 19.99]}

Upvotes: 1

Related Questions