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

Une bévue wrote:

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 ???

Use << (or concat).

···

--
Alex

Alex Young wrote:

Une bévue wrote:

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 ???

Use << (or concat).

or sub!.

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

···

--
Alex

Alex Young 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:

Alex Young wrote:

Use << (or concat).

or sub!.

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

Oh yes. So it would :slight_smile:

···

--
Alex

with is the reason for this line ???

···

Daniel DeLorme <dan-ml@dan42.com> wrote:

   alias copy *

--
une bévue

thanxs to all !

···

Alex Young <alex@blackkettle.org> wrote:

Oh yes. So it would :slight_smile:

--
une bévue

Une bévue wrote:

···

Daniel DeLorme <dan-ml@dan42.com> 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

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

···

Alex Young <alex@blackkettle.org> 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"

--
une bévue