我从txt文件初始化了一个哈希。如果我没有弄错,那么密钥当前是一个字符串。我怎样才能使它成为整数?任何帮助将不胜感激。
代码:
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
文件:
199, Shoes, 59.99
211, Shirts, 19.99
245, Hats, 25.99
689, Coats, 99.99
712, Beanies, 6.99
我的结果是:
{"199"=>["Shoes", 59.99], "211"=>["Shirts", 19.99], "245"=>["Hats", 25.99], "689"=>["Coats", 99.99], "712"=>["Beanies", 6.99]}
答案 0 :(得分:3)
我会做Hash[ hash.keys.map(&:to_i).zip(hash.values) ]
答案 1 :(得分:1)
您可以使用inject
使用整数键构建新哈希:
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]}