查找 ruby 数组中的整数 (Fixnum) 值
我有一个带有
- 纯整数的数组
[1, 2, "3", "4", "1a", "abc", "a"]
(1
, < code>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]
但是这个将 "1a"
转换为 1
,这是我不期望的。
然后我尝试了Integer(item)
:
arr.map {|x| Integer(x) } # and it turned out to be
# => ArgumentError: invalid value for Integer(): "1a"
现在我在这里没有直接转换选项。最后,我决定这样做,将值 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
现在
ids, names= arr.partition { |item| item.kind_of? Fixnum }
我得到了整数和字符串数组。有没有一种简单的方法可以做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
与 @maerics 提供的类似解决方案,但更精简:
Similar solution as provided by @maerics, but a bit slimmer:
像这样的东西:
something like this:
嘿,谢谢唤醒我的红宝石。这是我解决这个问题的方法:
Hey, thanks awakening my ruby. Here is my go at this problem:
我注意到到目前为止,大多数答案都将“3”和“4”的值更改为实际整数。
@OP,我还没有彻底测试我的解决方案,但到目前为止它似乎有效(当然它是根据提供的示例完成的),所以请自己彻底测试。
I noticed most of the answer so far changes the value of "3" and "4" to actual integers.
@OP, I have not tested my solution exhaustively, but so far it seems to work (of course its done according to provided sample ), so please test thoroughly yourself.
这个怎么样?
How about this?
看起来很简单
Looks pretty simple