Reputation: 300
I have a loop, and in it want to assign a string to the value of i + (i-1) but am not sure how to progress.
(1..50).each do |i|
answer = "#{i+(i-1)}"
end
In this code the answer must be a string as it will eventually relate to a database table.
What is the best way of evaluating this within the string, I have tried a few variations of this but haven't had any luck so any helpful pointers would be much appreciated.
Upvotes: 0
Views: 84
Reputation: 11
Maybe something like this?
(1..50).map{|i| i + (i-1)}.map(&:to_s)
Map
will take Rage
and perform addition written in block on each element and then return transformed Array
(Array
and Range
are enumerable types) which we pass once more to map
and &:to_s
is ruby's syntactic sugar that turns to_s
into a block that can be passed to map. It is equal to .map {|i| i.to_s}
Upvotes: 1