如果我有这个数组:
["1","2","3,a","4,b"]
我怎样才能从中得到这个数组?
["1","2","3","4"].
假设你有所有整数,(如果没有,我猜你明白了:))
["1","2","3,a","4,b"].collect {|i| i.to_i}
使用如下数组:
ary = ["1","2","3,a","4,b"]
我会使用:
ary.map{ |s| s[/\A(\d+)/, 1] }
结果是:
[ [0] "1", [1] “2”, [2] “3”, [3] “4” ]
它只是在字符串的开头找到数字并将它们返回到一个新数组中。
尝试:
["1","2","3,a","4,b"].map(&:to_i)
=> [1, 2, 3, 4]
获取字符串数组
["1","2","3,a","4,b"].map(&:to_i).map(&:to_s)
=> ["1", "2", "3", "4"]
这也应该有效......
array=["1","2","3,a","4,b"]
for i in 0..array.length()-1
if array[i].include?(",")
ab=array[i].split(",")
array[i]=ab[0]
end
end
print array #["1","2","3","4"]
试试这个删除选项:
irb(main):014:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):015:0> count = a.count
irb(main):016:0> for i in 0..count
irb(main):017:1> puts a[i].delete("^0-9")
irb(main):018:1> end
101
2
3
10
更新的代码(每个循环的使用 - 感谢 Tin Man)
irb(main):005:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):006:0> b = []
=> []
irb(main):007:0> a.each do |t|
irb(main):008:1* b << t.delete("^0-9")
irb(main):009:1> end
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):010:0> puts b
101
2
3
10
=> nil