[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

How can I write this method in one line?

Jigar Gosar

2/14/2008 10:09:00 AM

def gen_indices_string num
string = ""
num.times{|i| string<<(i+1).to_s}
return string
end

I have a feeling that stuff can be written in a single line using some
of the ruby API. Can anyone help?

thanks
--
Posted via http://www.ruby-....

3 Answers

Sebastian Hungerecker

2/14/2008 10:26:00 AM

0

Jigar Gosar wrote:
> def gen_indices_string num
> string = ""
> num.times{|i| string<<(i+1).to_s}
> return string
> end
>
> I have a feeling that stuff can be written in a single line using some
> of the ruby API. Can anyone help?

(1..num).to_a.join
or
(1..num).inject("") {|str,i| str << i.to_s}

--
Jabber: sepp2k@jabber.org
ICQ: 205544826

Jigar Gosar

2/14/2008 10:36:00 AM

0

Sebastian Hungerecker wrote:
> Jigar Gosar wrote:
>> def gen_indices_string num
>> string = ""
>> num.times{|i| string<<(i+1).to_s}
>> return string
>> end
>>
>> I have a feeling that stuff can be written in a single line using some
>> of the ruby API. Can anyone help?
>
> (1..num).to_a.join
> or
> (1..num).inject("") {|str,i| str << i.to_s}

thanks, I knew there was a better way :)
--
Posted via http://www.ruby-....

Johan Veenstra

2/14/2008 12:02:00 PM

0

[Note: parts of this message were removed to make it a legal post.]

irb(main):033:0> num = 10
=> 10

irb(main):037:0> "%s"*num % (1..num).to_a
=> "12345678910"

irb(main):036:0> "%4s"*num % (1..num).to_a
=> " 1 2 3 4 5 6 7 8 9 10"

irb(main):035:0> "%-4s"*num % (1..num).to_a
=> "1 2 3 4 5 6 7 8 9 10 "

irb(main):034:0> (["%4s"]*num).join("|") % (1..num).to_a
=> " 1| 2| 3| 4| 5| 6| 7| 8| 9| 10"

2008/2/14, Sebastian Hungerecker <sepp2k@googlemail.com>:
>
> Jigar Gosar wrote:
> > def gen_indices_string num
> > string = ""
> > num.times{|i| string<<(i+1).to_s}
> > return string
> > end
> >
> > I have a feeling that stuff can be written in a single line using some
> > of the ruby API. Can anyone help?
>
> (1..num).to_a.join
> or
> (1..num).inject("") {|str,i| str << i.to_s}
>
> --
> Jabber: sepp2k@jabber.org
> ICQ: 205544826
>
>