Clone array elements

G

Guilherme Mello

How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Thanks.
 
G

Guilherme Mello

Guilherme said:
How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Thanks.

I solve this using this method:

def repeat n
new_array = Array.new
self.each { |x| n.times do new_array.push x end }
new_array
end

Thanks.
 
R

Riccardo Cecolin

Guilherme said:
How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Thanks.
like this?

irb(main):018:0> a=[:eek:ne,"two",3]
=> [:eek:ne, "two", 3]
irb(main):019:0> n=3; res=[]; a.each { |e| n.times { |i| res.push e } }; res
=> [:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]
 
H

Heesob Park

Hi,

2010/3/12 Guilherme Mello said:
How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]
You can do it like this:

irb(main):003:0> [:eek:ne,"two",3].map{|x|[x]*3}.flatten(1)
=> [:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Regards,

Park Heesob
 
H

Harry Kakueki

How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Another way maybe,

class Array
def repeat(num)
Array.new(num,self).transpose.flatten
end
end

p [:eek:ne,"two",3].repeat(3) #> [:eek:ne, :eek:ne, :eek:ne, "two", "two",
"two", 3, 3, 3]



Harry
 
R

Robert Klemme

2010/3/13 Harry Kakueki said:
How to create the repeat method:

[:eek:ne, "two", 3].repeat(3)

Result:

[:eek:ne, :eek:ne, :eek:ne, "two", "two", "two", 3, 3, 3]

Another way maybe,

class Array
=A0def repeat(num)
=A0 =A0Array.new(num,self).transpose.flatten
=A0end
end

p [:eek:ne,"two",3].repeat(3) =A0 =A0#> [:eek:ne, :eek:ne, :eek:ne, "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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top