I wrote that the newbie way, but is there any way to DRY it ?
closed_cities = []
0.step(9, 1) do |i|
closed_cities << City.find_by_id( city_25 [i] [0] )
i = i.next
end
if yes, is it only for fun , or does it impact performance (a lot ?)
thanks for your lights
joss
On 12/19/06, Josselin [email protected] wrote:
I wrote that the newbie way, but is there any way to DRY it ?
closed_cities = []
0.step(9, 1) do |i|
closed_cities << City.find_by_id( city_25 [i] [0] )
i = i.next
end
if yes, is it only for fun , or does it impact performance (a lot ?)
i = i.next is unecessary, the step method updates the loop for you. Also
you
can use upto instead of step:
0.upto(9) do |i|
closed_cities << City.find_by_id( city_25[i][0] )
end
Or instead of using upto you can use a range:
(0…9).each do |i|
closed_cities << City.find_by_id( city_25[i][0] )
end
But now you realize, hey if I’m gonna use a range, I can use map, so now
you
make your code one line:
closed_cities = (0…9).map { |i| City.find_by_id( city_25[i][0] ) }
I would suggest checking out the docs for Range, as well as for step,
upto,
times each and map.
thanks for your lights
On 12/19/06, Josselin [email protected] wrote:
I wrote that the newbie way, but is there any way to DRY it ?
closed_cities = []
0.step(9, 1) do |i|
closed_cities << City.find_by_id( city_25 [i] [0] )
i = i.next
end
if yes, is it only for fun , or does it impact performance (a lot ?)
Not sure where the “wet” bit is, but the “i = i.next” is redundant, as
‘i’ gets assigned on each call of the block.
Without knowing more about what each thing is/does, I’d recommend:
closed_cities = (0…9).map{|i| City.find_by_id(city_25[i][0])}
thanks for your lights
Welcome!