2014-11-01 65 views
0

我从一个CSV文件中读取与成为访问数组值

parse = [["742", "Rewards", "0.309", "0.249", "0.0195", "0.1"], ["742", "Reg (DB)", "0.165", "0.194", "0.0005", "0.21"]] 

我试图在阵列内访问阵列和解析更改文本格式整数和浮点数的数组。我当前的代码如下:

require 'CSV' 

parse = CSV.read("testDB.csv") 
parse.map do |code, cat, pervol, percnt, rate, fee| 
    code.to_i 
    pervol.to_f 
    percnt.to_i 
    rate.to_f 
    fee.to_f 
end 

我是新来的Ruby和知道这是不正确,但我无法找到正确的组合,相应地改变阵列。任何人都可以提供解决方案吗?

回答

0

你想做到这一点?:

parse.map{ |r| [r[0].to_i, r[1], r[2].to_f, r[3].to_f, r[4].to_f, r[5].to_f] } 
#=> [[742, "Rewards", 0.309, 0.249, 0.0195, 0.1], [742, "Reg (DB)", 0.165, 0.194, 0.0005, 0.21]] 

parse是数组的数组,因此,在map你必须访问数组对象,其索引,然后做相应的操作。

由于约尔格W¯¯米塔格指出的那样,你可以用这样的解构绑定和有意义的变量名(这有助于了解哪些对象就是数组中)做到这一点:

parse.map{ |code, cat, pervol, percnt, rate, fee| [code.to_i, cat, pervol.to_f, percnt.to_f, rate.to_f, fee.to_f] } 
+0

啊谢谢你,这样过尝试它,当我错过了阵列支架,现在我明白了。谢谢! – heinztomato 2014-11-02 01:05:18

+0

如果使用解构绑定和有意义的变量名称而不是无意义的索引,这将更容易阅读:''parse.map {| code,cat,pervol,percnt,rate,fee | [code.to_i,cat,pervol.to_f,percnt.to_f,rate.to_f,fee.to_f]}' – 2014-11-02 01:58:14

+0

@JörgWMittag:这真的很有帮助。感谢您的见解。 – Surya 2014-11-02 08:42:21

0

我建议如下:

parse = [["742", "Rewards", "0.309", "0.249", "0.0195", "0.1"], 
     ["742", "Reg (23)", "0.165", "0.194", "0.0005", "0.21"]] 

parse.map do |arr| 
    arr.map do |e| 
    case e 
    when /^\d+$/ then e.to_i 
    when /^\d+\.\d+$/ then e.to_f 
    else e 
    end 
    end 
end 
    #=> [[742, "Rewards", 0.309, 0.249, 0.0195, 0.1], 
    # [742, "Reg (23)", 0.165, 0.194, 0.0005, 0.21]]