How to create this array in Ruby?

Is there a smarter way to define such an array in Ruby?

array = [5, 15, 25, 35, 45, 55, 65, 75]

Thanks for any help.

+3
source share
4 answers

Use Range#step:

Range.new(5, 75).step(10).to_a
# => [5, 15, 25, 35, 45, 55, 65, 75]

[*Range.new(5, 75).step(10)]
# => [5, 15, 25, 35, 45, 55, 65, 75]

[*(5..75).step(10)]  # (5..75) == Range.new(5, 75)
# => [5, 15, 25, 35, 45, 55, 65, 75]
+6
source
5.step(75, 10).to_a #=> [5, 15, 25, 35, 45, 55, 65, 75]
+7
source

Not sure if this is better, but one way:

a = 8.times.map {|i| i*10+5} #=> [5, 15, 25, 35, 45, 55, 65, 75]

The advantage of this method is that the number of elements as a result of ( 8) is explicit.

+4
source

Here is one way:

>> Array.new(8) { |i| i*10 + 5 }
=> [5, 15, 25, 35, 45, 55, 65, 75]
>> 
+1
source

All Articles