仅选择特定元素

时间:2013-07-23 12:28:59

标签: ruby rhomobile

我有一个数组:

line = ["0;\t0\n", "1;\t0\n", "2;\t0\n", "3;\t0\n", "4;\t0\n", "5;\t0\n", "6;\t0\n", "7;\t0\n", "8;\t0\n", "9;\t0\n", "10;\t0\n", "11;\t0\n", "12;\t0\n", "13;\t0\n", "14;\t0\n", "15;\t0\n", "16;\t0\n", "17;\t0\n", "18;\t0\n", "19;\t0\n", "20;\t0\n", "21;\t4,8\n", "22;\t9,5\n", "23;\t13,8\n", "24;\t18,5"]

我想提取分号后面的值。是否可以提取值(0,0,0,...,4,8,9,5,13,​​6等)?我该怎么做?我试过了:

sa=line.split(";")
sa1=sa[1].delete "\n"
sa1=sa1.delete "\t"
sa1=sa1.to_i
$sa1 = sa1

当我显示$sa1时,我只会看到18,5

3 个答案:

答案 0 :(得分:1)

这很简单:

str = ["0;\t0\n", "1;\t0\n", "2;\t0\n", "3;\t0\n", "4;\t0\n", "5;\t0\n", "6;\t0\n", "7;\t0\n", "8;\t0\n", "9;\t0\n", "10;\t0\n", "11;\t0\n", "12;\t0\n", "13;\t0\n", "14;\t0\n", "15;\t0\n", "16;\t0\n", "17;\t0\n", "18;\t0\n", "19;\t0\n", "20;\t0\n", "21;\t4,8\n", "22;\t9,5\n", "23;\t13,8\n", "24;\t18,5"]

p str.map{|el| el.split(/;\t/)[1].chomp}

结果:

# ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "4,8", "9,5", "13,8", "18,5"]

答案 1 :(得分:0)

a=["0;\t0\n", "1;\t0\n", "2;\t0\n"]
p a.map{|i| i[0..i.index(';')-1]}
#>> ["0", "1", "2"]

a=["0;\t0\n", "1;\t0\n", "2;\t12\n"]
p a.map{|i| i[i.index("\t")+1..-1].chomp}
# >> ["0", "0", "12"]

答案 2 :(得分:0)

Sting#[]

line.map{|s| s[/;\s*(\S+)/, 1]}
# => ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "4,8", "9,5", "13,8", "18,5"]