2

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.

4 Answers 4

15

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]
Sign up to request clarification or add additional context in comments.

3 Comments

did not know that--very nice.
Very nice. FOr Ruby 1.8.6, just require 'backports'
Wow, would have never known about this. Perfect.
4
Array.new(12).fill(some_array).flatten[0..11]

Comments

3
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. :-)

3 Comments

Awesome, thanks! This is definitely a cleaner version of what I was coming up with.
I love that the method is called :twelvify :)
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! :)
1
array * (12/array.size) + array[0, (12 % array.size)]

3 Comments

Exactly what the OP asked for, but dear $deity it's ugly :)
How about: array * (12/array.size + 1))[0,12]
@sepp2k, did you mean ... instead of ..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.