我有一个数组[1, 2, "3", "4", "1a", "abc", "a"]与
1,2),"1","2"),"a","b")和"1a","2s").从此,我需要拿起唯一的整数(包括格式的字符串)1,2,"3","4".
首先我试过to_i:
arr = [1, 2, "3", "4", "1a", "abc", "a"]
arr.map {|x| x.to_i}
# => [1, 2, 3, 4, 1, 0, 0]
Run Code Online (Sandbox Code Playgroud)
但这个转换"1a"为1,我没想到.
然后我尝试了Integer(item):
arr.map {|x| Integer(x) } # and it turned out to be
# => ArgumentError: invalid value for Integer(): "1a"
Run Code Online (Sandbox Code Playgroud)
现在我没有直接的转换选项.最后,我决定这样做,转换价值to_i和to_s.所以"1" == "1".to_i.to_s是一个整数,但不是"1a" == "1a".to_i.to_s和"a" == "a".to_i.to_s
arr = arr.map do |x|
if (x == x.to_i.to_s)
x.to_i
else
x
end
end
Run Code Online (Sandbox Code Playgroud)
和
ids, names= arr.partition { |item| item.kind_of? Fixnum }
Run Code Online (Sandbox Code Playgroud)
现在我得到了整数和字符串数组.有一个简单的方法吗?
类似的解决方案由@maerics提供,但有点苗条:
arr.map {|x| Integer(x) rescue nil }.compact
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5720 次 |
| 最近记录: |