How do i use a loop to fill an array?

i am trying to use a loop to fill an array with numbers from 0 through
25, but i have no idea how to do it. Can someone please help? thank you

a = []
0.upto(25) { |n| a << n }

  • or -


Just a little help, you’re thinking about loops to fill arrays, and
that is where you’re getting stuck. In ruby, most “loops” are
iterators/closures, so I think you could start thinking about
closures. For example, the expects a parameter and a block,
or two parameters. So, if you want an array with 10 values, and set
all values to “string”, for example, you could use:, “string”)

Otherwise, if you want to populate the array based on the index of
each element, you could use the block version: { |index| index }

The block will “iterate”, starting on index 0 and ending on index 25
(26 elements) and return the index value. If you wanted, for example,
an array with the square of 0 through 10 you could use: { |index| index * index }

In your example, like Tony said, you could convert a range to a array.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs