0

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.

5
  • 1
    What result you want to see? Commented Apr 22, 2016 at 18:06
  • I want the answer in a format such that, if i = 20, the answer gives 39 etc Commented Apr 22, 2016 at 18:08
  • 2
    It might be useful to us to explain why you want to do this. Generally sticking code into a string and evaluating it isn't recommended, and there are ways in Ruby to dynamically generate code not using eval. Right now this sounds like an XY Problem and you're asking about Y instead of X. Commented Apr 22, 2016 at 18:08
  • Currently it just gives, 20+19 Commented Apr 22, 2016 at 18:08
  • 2
    Your code is fine. There's just not much point to it. When i=1, result is assigned to the string "1". When i=2, result is reassigned to "3", and so on. The loop returns the last value of result, which is "99". Perhaps you want Array.new(50) { |i| "#{2*i+1}" } #=> ["1", "3",..., "99"]. Commented Apr 22, 2016 at 19:00

1 Answer 1

1

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}

Sign up to request clarification or add additional context in comments.

1 Comment

Please don't use sth. Stack Overflow isn't a discussion forum, it's more like an online reference book. We value correct grammar and clarity. Also, please explain why the code is the solution to the problem. Simply handing out code only solves this problem. Explaining why to use it helps in the future when a similar problem occurs too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.