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?
arrays ruby range
Kiwi
source share