我是红宝石的新手。尝试使用方法获取数组中的所有数字。
x = [1..10]
预期结果。
=> [1,2,3,4,5,6,7,8,9,10]
答案 0 :(得分:4)
当您输入[1..10]
时,您实际拥有的是包含单个Array对象的Range。如果你想要一组FixNums,你实际上放弃[]
并在范围本身上调用to_a
:
irb(main):006:0> x = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
答案 1 :(得分:1)
你想要显示它吗?
# 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