How to create a list of numbers and use it effectively in Ruby

Given the minimum integer and maximum integer, I want to create an array that calculates from minimum to maximum two, then back off (again two, repeating the maximum number).

For example, if the minimum number is 1 and the maximum value is 9, I want [1, 3, 5, 7, 9, 9, 7, 5, 3, 1] .

I try to be as concise as possible, so I use single-line.

In Python, I would do the following:

 range(1, 10, 2) + range(9, 0, -2) 

In Ruby, which I am just starting to learn, all that I have come up with so far:

 (1..9).inject([]) { |r, num| num%2 == 1 ? r << num : r }.reverse.inject([]) { |r, num| r.unshift(num).push(num) } 

What works, but I know what should be the best way. What is it?

+6
arrays ruby range
source share
1 answer
 (1..9).step(2).to_a + (1..9).step(2).to_a.reverse 

But it would be shorter

 Array.new(10) { |i| 2 * [i, 9-i].min + 1 } 

if we play golf :)

+6
source share

All Articles