x
y
to_a?
现在我正在尝试
x.each do |s|
if s.to_i.is_a?(Integer)
y << s
end
end
但这只是将所有内容转换为整数并将其填入y
,有没有办法查看对象是否真的来自Integer类?
编辑添加样本输入/输出
x = [ "This", "is", "a", "random", "amalgamation", "of", "text", "and", "a",
"bunch", "of", "numbers", "111113087403957304739703975", "how", "can", "I",
"read", "this", "in." ]
y = [ 111113087403957304739703975 ]
答案 0 :(得分:4)
x = [ "This", "is", "a", "random", "amalgamation", "of", "text", "and", "a",
"bunch", "of", "numbers", "111113087403957304739703975", "how", "can", "I",
"read", "this", "in." ]
y = [ 111113087403957304739703975 ]
def extract_integers(array)
array.select { |v| v.match(/\A\d+\z/) }.map(&:to_i)
# or (simpler, as suggested by @theTinMan)
array.reject { |v| v[/\D/] }.map(&:to_i)
end
p extract_integers(x) #=> [111113087403957304739703975]
p extract_integers(x) == y #=> true
答案 1 :(得分:3)
s.match(/^\d+$/)
将匹配仅包含数字的字符串,因此您可以使用此字符串来测试字符串
答案 2 :(得分:3)
您可以使用Enumerable#grep:
arr = %w[9 cats on 33 hot tin roofs]
#=> ["9", "cats", "on", "33", "hot", "tin", "roofs"]
arr.grep /^\d+$/
#=> ["9", "33"]
arr.grep(/^\d+$/).map(&:to_i)
#=> [9, 33]
答案 3 :(得分:1)
x.each do |s|
begin
Integer(s)
rescue ArgumentError
else
y << s
end
end
如果应用于不解析为整数的字符串,Integer()
会引发ArgumentError
。您可以使用它来查找整数字符串。
答案 4 :(得分:1)
运行基准测试总是很有趣,也很有用:
require 'fruity'
x = [ "This", "is", "a", "random", "amalgamation", "of", "text", "and", "a",
"bunch", "of", "numbers", "111113087403957304739703975", "how", "can", "I",
"read", "this", "in." ]
def extract_integers(array)
array.select { |v| v.match(/\A\d+\z/) }.map(&:to_i)
end
def extract_integers_reject(array)
array.reject { |v| v[/\D/] }.map(&:to_i)
end
compare do
use_exception {
y = []
x.each do |s|
begin
Integer(s)
rescue ArgumentError
else
y << s.to_i
end
end
y
}
use_extract_integers {
extract_integers(x)
}
use_extract_integers_reject {
extract_integers_reject(x)
}
end
在我的机器上运行会产生以下结果:
Running each test 256 times. Test will take about 1 second.
use_extract_integers_reject is faster than use_extract_integers by 30.000000000000004% ± 10.0%
use_extract_integers is faster than use_exception by 6x ± 0.1
注意,y << s
已更改为y << s.to_i
,以使输出全部匹配。
我可能会使用像这样的ArgumentError救援来简化代码:
x.each do |s|
begin
y << Integer(s)
rescue ArgumentError
end
end