How to create list of numbers and append its reverse to it efficiently in Ruby
        Posted  
        
            by Kiwi
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Kiwi
        
        
        
        Published on 2010-05-12T19:35:45Z
        Indexed on 
            2010/05/12
            19:54 UTC
        
        
        Read the original article
        Hit count: 307
        
Given a minimum integer and maximum integer, I want to create an array which counts from the minimum to the maximum by two, then back down (again by two, repeating the maximum number).
For example, if the minimum number is 1 and the maximum is 9, I want [1, 3, 5, 7, 9, 9, 7, 5, 3, 1].
I'm trying to be as concise as possible, which is why I'm using one-liners.
In Python, I would do this:
range(1, 10, 2) + range(9, 0, -2)
In Ruby, which I'm just beginning to learn, all I've come up with so far is:
(1..9).inject([]) { |r, num| num%2 == 1 ? r << num : r }.reverse.inject([]) { |r, num| r.unshift(num).push(num) }
Which works, but I know there must be a better way. What is it?
© Stack Overflow or respective owner