Tintin81
Tintin81

Reputation: 10207

How to create this array in Ruby?

I there a smarter way to define an array like this in Ruby?

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

Thanks for any help.

Upvotes: 3

Views: 97

Answers (4)

steenslag
steenslag

Reputation: 80065

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

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118271

Here is one way :

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

Upvotes: 1

berkes
berkes

Reputation: 27553

Not sure if it is nicer, but one way would be:

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

The benefit of this method, is that the amount of items in the result (8) is explicit.

Upvotes: 4

falsetru
falsetru

Reputation: 369074

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]

Upvotes: 6

Related Questions