在ruby数组中查找整数(Fixnum)值

Ram*_*Vel 2 ruby fixnum

我有一个数组[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_ito_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)

现在我得到了整数和字符串数组.有一个简单的方法吗?

int*_*iot 6

类似的解决方案由@maerics提供,但有点苗条:

arr.map {|x| Integer(x) rescue nil }.compact
Run Code Online (Sandbox Code Playgroud)

  • 我想发布几乎相同,但使用`select`就像这样:`>> a.select {| i | 整数(i)拯救虚假}#=> [1,2,"3","4"]`.无论如何,由于解决方案是如此相似,我会让你有这个.:-) (2认同)