From: Robert Klemme on
2010/3/13 Harry Kakueki <list.push(a)gmail.com>:
> On Fri, Mar 12, 2010 at 11:33 PM, Guilherme Mello <javaplayer(a)gmail.com> wrote:
>> How to create the repeat method:
>>
>> [:one, "two", 3].repeat(3)
>>
>> Result:
>>
>> [:one, :one, :one, "two", "two", "two", 3, 3, 3]
>>
>
> Another way maybe,
>
> class Array
>  def repeat(num)
>    Array.new(num,self).transpose.flatten
>  end
> end
>
> p [:one,"two",3].repeat(3)    #> [:one, :one, :one, "two", "two",
> "two", 3, 3, 3]

This is nice!

Since we didn't have #inject in a long time:

module Enumerable
def repeat(n)
inject [] do |res, it|
n.times { res << it }
res
end
end
end

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/