gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:15:00 26 4
gpt4 key购买 nike

我有一个数组 [1, 2, "3", "4", "1a", "abc", "a"]

  • 纯整数(12),
  • 字符串格式的整数(“1”“2”),
  • 字符串(“a”“b”)和
  • 混合字符串数字(“1a”“2s”)。

由此,我只需要选取整数(包括字符串格式)12"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]

但是这个将 "1a" 转换为 1,这是我不期望的。

然后我尝试了Integer(item):

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

现在我没有直接的转换选项了。最后,我决定这样做,它将值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

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

现在我得到了整数和字符串数组。有没有简单的方法可以做到这一点?

最佳答案

@maerics 提供的类似解决方案,但更简洁:

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

关于ruby - 在 ruby​​ 数组中查找整数 (Fixnum) 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com