Ruby – To find the integer (Fixnum) values in ruby array

fixnumruby

I have an array [1, 2, "3", "4", "1a", "abc", "a"] with

  • pure integers (1, 2),
  • string formatted integers ("1", "2"),
  • strings ("a", "b"), and
  • mixed string numbers ("1a", "2s").

From this, I need to pick up only the integers (including string formatted) 1, 2, "3", "4".

First I tried with to_i:

arr = [1, 2, "3", "4", "1a", "abc", "a"]
arr.map {|x| x.to_i}
# => [1, 2, 3, 4, 1, 0, 0]

but this one converts "1a" to 1, which I don't expect.

Then I tried Integer(item):

arr.map {|x| Integer(x) }  # and it turned out to be
# => ArgumentError: invalid value for Integer(): "1a"

Now I am out of straight conversion options here. Finally, I decided to do this way, which converts the value to_i and to_s. So "1" == "1".to_i.to_s is an integer, but not "1a" == "1a".to_i.to_s and "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

and

ids, names= arr.partition { |item| item.kind_of? Fixnum }

Now I got the arrays of integers and strings. Is there a simple way to do this?

Best Answer

Similar solution as provided by @maerics, but a bit slimmer:

arr.map {|x| Integer(x) rescue nil }.compact