tags:

views:

129

answers:

4

I'm looking to write a method that creates an array of a fixed length (in my case 12) from any array it is provided of arbitrary length (though the length will always be 12 or less) by repeating the objects in order.

So for example given the array a:

a = [1, 2, 3, 4]

I would want to have returned:

a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

Another example:

b = ["peach", "plumb", "pear", "apple", "banana", "orange"]

Would return:

b = ["peach", "plumb", "pear", "apple", "banana", "orange", "peach", "plumb", "pear", "apple", "banana", "orange"]

And so on. If given an array with 12 objects, it would just return the same array.

The methods I've written to accomplish this so far have been very ugly and not very Rubyish; interested in how others would handle this.

Thanks in advance.

+3  A: 
def twelvify array
  array += array while array.size < 12
  array[0..11]
end

It's also a bit ugly but it's, at least, simple. :-)

Trevoke
Awesome, thanks! This is definitely a cleaner version of what I was coming up with.
Bryan Woods
I love that the method is called `:twelvify` :)
James A. Rosen
*chuckle* Yep, I definitely got a good Rubyish name for it, but I have to admit that I like BarqueBobcat's answer a lot more than mine! :)
Trevoke
A: 
array * (12/array.size) + array[0, (12 % array.size)]
sepp2k
Exactly what the OP asked for, but dear $deity it's ugly :)
Trevoke
How about: array * (12/array.size + 1))[0,12]
Farrel
@sepp2k, did you mean ... instead of ..?
Wayne Conrad
@Wayne: Yes, that or ",". Thanks for the correction.
sepp2k
+2  A: 
Array.new(12).fill(some_array).flatten[0..11]
floyd
+10  A: 

In 1.8.7 & 1.9 you can do cool stuff with Enumerators

a = [1,2,3,4]
#=> [1,2,3,4]
a.cycle.take 12
#=> [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
BaroqueBobcat
did not know that--very nice.
floyd
Very nice. FOr Ruby 1.8.6, just `require 'backports'`
Marc-André Lafortune
Cool! I like it.
Trevoke
Wow, would have never known about this. Perfect.
Bryan Woods