如何在ruby中显示数组的所有整数?
我是ruby的新手。 尝试使用方法获取数组中的所有数字。
x = [1..10]
预期结果。
=> [1,2,3,4,5,6,7,8,9,10]
键入[1..10]
,实际拥有的是包含单个Range对象的Array 。 如果你想要一个FixNums数组,你实际上删除了[]
并在范围本身上调用to_a
:
irb(main):006:0> x = (1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
你想要显示它吗?
# This dumps the object to console x = (1..10).to_a puts x.inspect # This prints items individually... x = (1..10).to_a x.each do |num| puts num end # This prints only numbers.... x = (1..10).to_a x.each do |num| if num.is_a?(Integer) puts num end end