How to create the repeat method:
[:one, “two”, 3].repeat(3)
Result:
[:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
Thanks.
How to create the repeat method:
[:one, “two”, 3].repeat(3)
Result:
[:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
Thanks.
Guilherme M. wrote:
How to create the repeat method:
[:one, “two”, 3].repeat(3)
Result:
[:one, :one, :one, “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.
Guilherme M. wrote:
How to create the repeat method:
[:one, “two”, 3].repeat(3)
Result:
[:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
Thanks.
like this?
irb(main):018:0> a=[:one,“two”,3]
=> [:one, “two”, 3]
irb(main):019:0> n=3; res=[]; a.each { |e| n.times { |i| res.push e } };
res
=> [:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
On Fri, Mar 12, 2010 at 11:33 PM, Guilherme M. [email protected]
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]
Harry
2010/3/13 Harry K. [email protected]:
Another way maybe,
class Array
def repeat(num)
Array.new(num,self).transpose.flatten
end
endp [: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
Hi,
2010/3/12 Guilherme M. [email protected]:
How to create the repeat method:
[:one, “two”, 3].repeat(3)
Result:
[:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
You can do it like this:
irb(main):003:0> [:one,“two”,3].map{|x|[x]*3}.flatten(1)
=> [:one, :one, :one, “two”, “two”, “two”, 3, 3, 3]
Regards,
Park H.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs