Extending String call with a #copy!(n)

i’ve allready extendy String class by a #copy(n) like that :

class String
def copy(n)
out=""
(1…n).each {|i| out+=self}
return out
end
end

however i’d like to extend also String with a #copy!(n) (in place which
would work like that :

“*”.copy!(4)

=> “****”

the prob is to affect self ???

Une bévue wrote:

however i’d like to extend also String with a #copy!(n) (in place which
would work like that :

“*”.copy!(4)

=> “****”

the prob is to affect self ???

Use << (or concat).

Alex Y. wrote:

however i’d like to extend also String with a #copy!(n) (in place which
would work like that :

“*”.copy!(4)

=> “****”

the prob is to affect self ???

Use << (or concat).

or sub!.

class String
def copy!(n)
self.sub!(self, self*n)
end
end

Alex Y. wrote:

Use << (or concat).

or sub!.

replace would be more efficient:
class String
alias copy *
def copy!(n)
replace(self*n)
end
end

Daniel DeLorme wrote:

end
end

Oh yes. So it would :slight_smile:

Daniel DeLorme [email protected] wrote:

alias copy *

with is the reason for this line ???

Une bévue wrote:

Daniel DeLorme [email protected] wrote:

alias copy *

with is the reason for this line ???

Your copy method produces identical results to the String#* method. For
example:

irb(main):001:0> a = “foo”
=> “foo”
irb(main):002:0> a * 3
=> “foofoofoo”

Alex Y. [email protected] wrote:

Your copy method produces identical results to the String#* method. For
example:

irb(main):001:0> a = “foo”
=> “foo”
irb(main):002:0> a * 3
=> “foofoofoo”

OK, fine, thanxs, i even didn’t notice the ruby facility upon String
multiplication :wink:

Alex Y. [email protected] wrote:

Oh yes. So it would :slight_smile:

thanxs to all !

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs