How can I write this method in one line?

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

Jigar G. 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}

Sebastian H. wrote:

Jigar G. 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 :slight_smile:

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 H. [email protected]: