如果我有这个数组:
["1","2","3,a","4,b"]
如何从中获取此数组?
["1","2","3","4"].
答案 0 :(得分:9)
假设你有所有整数,(如果不是我猜你得到了这个想法:))
["1","2","3,a","4,b"].collect {|i| i.to_i}
答案 1 :(得分:3)
使用如下数组:
ary = ["1","2","3,a","4,b"]
我会用:
ary.map{ |s| s[/\A(\d+)/, 1] }
结果是:
[ [0] "1", [1] "2", [2] "3", [3] "4" ]
它只是在字符串的开头找到数字并将它们返回到一个新数组中。
答案 2 :(得分:1)
尝试:
["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"]
答案 3 :(得分:0)
这也应该有效......
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"]
答案 4 :(得分:-2)
尝试此删除选项:
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
更新代码(每个循环的使用 - 感谢锡人)
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