Ruby从float到integer的散列数组中更改类型

时间:2013-07-25 11:52:32

标签: ruby-on-rails ruby

我有这样的数组数据:

[#<PriceList id: 463134, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22", price: 5405.0, quantity: "50", waittime: 1, description: "Фильтр масл OPEL 1.2-3.0L (OC90)", created_at: "2013-01-30 16:35:34", updated_at: "2013-01-30 16:35:34", art_group: "Фильтр масл OPEL 1.2-3.0L (OC90)", oem_number: nil>, #<PriceList id: 517164, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22", price: 5442.0, quantity: "500", waittime: 3, description: "Фильтр масляный OPEL/GM/DAEWOO", created_at: "2013-01-30 16:42:26", updated_at: "2013-01-30 16:42:26", art_group: "Фильтр масляный OPEL/GM/DAEWOO", oem_number: nil>, #<PriceList id: 463135, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22(10)", price: 5101.0, quantity: "20", waittime: 1, description: "Фильтр масл.без упак.OPEL/GM (OC90Of)", created_at: "2013-01-30 16:35:34", updated_at: "2013-01-30 16:35:34", art_group: "Фильтр масл.без упак.OPEL/GM (OC90Of)", oem_number: nil>, ... etc

我该如何更改价格类型?

我试试

@non_original2 = @non_original2.map { |e| e[:price].to_i }

但结果我只看到价格值...如何更改我的数组,以便所有哈希值中的价格字段变为整数值?

1 个答案:

答案 0 :(得分:2)

怎么样

@non_original2.each { |e| e[:price] = e[:price].to_i }

这会更改列表中的每个PriceList项目(并且不会复制列表)。

使用您的方法会生成价格值列表,因为map会收集块的结果e[:price].to_i的结果是整数(您看到的价格)。