Ruby 如何遍历混合类型数组并返回第一个整数
给定的Ruby 如何遍历混合类型数组并返回第一个整数,ruby,Ruby,给定的x: x = ["stuff", "111", "other stuff", "more stuff"] 如果整数(在本例中为“111”)可以是任何正整数,那么如何将整数111返回到变量,并理想地将其从数组中删除?我认为您希望查找的是字符串数字,而不是整数,因此您必须测试一个全是数字的字符串 found = nil for elem in x do if elem =~ /^[0-9]+$/ found = elem break end end found
x
:
x = ["stuff", "111", "other stuff", "more stuff"]
如果整数(在本例中为“111”)可以是任何正整数,那么如何将整数
111
返回到变量,并理想地将其从数组中删除?我认为您希望查找的是字符串数字,而不是整数,因此您必须测试一个全是数字的字符串
found = nil
for elem in x do
if elem =~ /^[0-9]+$/
found = elem
break
end
end
found
你可以用
也许有点不同:
x = ["stuff", "111", "other stuff", "more stuff"]
found = x.select { |item| item == item.to_i.to_s } # (1)
p found
# => ["111"]
x -= found (2)
p x
# => ["stuff", "other stuff", "more stuff"]
在(1)
中,我们选择了所有要转换为Integer
的项目,并再次将Integer
转换为字符串,这样我们就可以比较值是否相同
"111".to_i
# => 111
但是
所以对于非整数字符串,这总是错误的
找到
项后,您可以通过x-=found
将它们从x
中删除,这是一个正整数吗?还是所有的正整数?是否要删除负整数?如果这不是您想要的,将更新答案
以下是我的想法:
x = ["stuff", "111", "other stuff", "more stuff", "-12"]
int = x.grep(/^\d+$/).shift.to_s.to_i
i = x.index("#{int}")
x.delete_at(i)
事实上,“111”不是一个整数,如果你做了“111”。class
它返回字符串
111
是一个Int
数组中没有任何整数。你是说表示整数的字符串吗?“e2”
和/或“3f”
是否合格?“返回整数到变量”是什么意思?很抱歉造成混淆。我在寻找一种方法来测试字符串中的整数并返回它。那么“-10”、“2.1”和“12A”呢?
"hello".to_i
# => 0
x = ["stuff", "111", "other stuff", "more stuff", "-12"]
int = x.grep(/^\d+$/).shift.to_s.to_i
i = x.index("#{int}")
x.delete_at(i)
x.detect { |n| n =~ /^[0-9]+$/ }