From: 7stud -- Date: 2011-05-25T07:53:54+09:00 Subject: Re: Generating Functions in Ruby 7stud -- wrote in post #1000754: > Andreas Lundgren wrote in post #1000535: >> First params does not contain a simple string; >> please note the escaped string characters in the code >> that generates params. Kind of strings within strings > > What I failed to recognize was that the line: > > params = #{params} > > was part of a multiline string. > > > >> "1) Strings are mutable in ruby, so get rid of all those +'s." - I'm >> not sure that I understand this but it sounds interesting, what does >> it mean? >> > > Every quoting mechanism creates a string and every + creates a new > combined string. So it's more efficient to use string interpolation: > > i = 2 > params = 'x1.to_s' > params = "#{params}, x#{i}.to_s" > p params > > --output:-- > "x1.to_s, x2.to_s" > > > In ruby not only can you push elements onto an array with the << method, > you can also use the << method to push a string onto another > string--which > alters the first string: > > > i = 2 > params = 'x1.to_s' > params = "#{params}, x#{i}.to_s" > > puts params > puts params.object_id > > params << ', x3.to_s' > > puts params > puts params.object_id > > --output:-- > x1.to_s, x2.to_s > 77684510 > x1.to_s, x2.to_s, x3.to_s > 77684510 So your loop here: params = 'x1.to_s'; for i in 2..no_of_params do arg_list = arg_list + ', x' + i.to_s; params = params + ' + \', \' + x' + i.to_s + '.to_s'; end params = params+';'; would simplify to: num_params = 4 params = 'x1.to_s' 2.upto(num_params).each do |i| params << ", x#{i}.to_s" end p params --output:-- "x1.to_s, x2.to_s, x3.to_s, x4.to_s" Also, compare that output to the output your loop produces: "x1.to_s + ', ' + x2.to_s + ', ' + x3.to_s + ', ' + x4.to_s" You would get many errors using that string as an argument list for a method. -- Posted via http://www.ruby-forum.com/.