how to show all integers of an array in ruby?

后端 未结 2 673
走了就别回头了
走了就别回头了 2021-01-16 07:53

I\'m new for ruby. Trying to get all numbers in an array with an method.

x = [1..10]

expected result.

=> [1,2,3,4,5,6,7,         


        
相关标签:
2条回答
  • 2021-01-16 08:10

    When you type [1..10], what you actually have is an Array containing a single Range object. If you want an array of FixNums, you actually drop the []s and call to_a on the range itself:

    irb(main):006:0> x = (1..10).to_a
    => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    0 讨论(0)
  • 2021-01-16 08:29

    you want to display it?

    # 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
    
    0 讨论(0)
提交回复
热议问题