[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

extending String call with a #copy!(n

pere.noel

8/10/2006 12:09:00 PM


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
8 Answers

Alex Young

8/10/2006 12:13:00 PM

0

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

8/10/2006 12:17:00 PM

0

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

Daniel DeLorme

8/10/2006 12:23:00 PM

0

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

Alex Young

8/10/2006 12:24:00 PM

0

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 :-)

--
Alex

pere.noel

8/10/2006 12:31:00 PM

0

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

> alias copy *

with is the reason for this line ???
--
une bévue

pere.noel

8/10/2006 12:31:00 PM

0

Alex Young <alex@blackkettle.org> wrote:

> Oh yes. So it would :-)

thanxs to all !
--
une bévue

Alex Young

8/10/2006 1:36:00 PM

0

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

pere.noel

8/10/2006 4:06:00 PM

0

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"

OK, fine, thanxs, i even didn't notice the ruby facility upon String
multiplication ;-)
--
une bévue