0

I would like to know if it is possible to set local variables in Ruby for loop.

More precisely I would like to have the for loop to behave like this:

tmp = 0
1.upto(5) { |i;tmp| puts i; tmp = i; } ; "tmp: #{tmp}"

The tmp variable should not be modified by what runs inside the foor loop.

6
  • Right, sorry for misguiding comment. Commented Nov 22, 2017 at 12:31
  • What are you trying to achieve? If you don't want a variable from outside get changed inside a loop, then don't change it. What is the point of assignment inside loop, if you don't want it to change? Commented Nov 22, 2017 at 12:58
  • I would like to use the for loop as i do in other programming languages, to keep a common pattern. It would be a substantial benefit to be able to definire local variables in the loop, i don't think i need to argument why it is so. Commented Nov 22, 2017 at 13:21
  • When I run your code, the outer tmp is indeed not modified. The block-local variable tmp masks it. How is this is not what you want? Commented Nov 22, 2017 at 16:09
  • @max, I don't understand well your question. The behaviour in the example is what i want. I was asking for a way to achieve that in a for loop. Commented Nov 22, 2017 at 17:24

2 Answers 2

1

You can introduce a new block for masking the outer variable

tmp = 0
for i in (1..5) do
  proc do |;tmp|
    puts i
    tmp = i
  end[]
end

This is awful. The difference between for and each is that the iteration variable in a for loop pollutes the outer scope.

x = []
# i has same scope as x
for i in (1..3)
  # closure captures i outside the loop scope, so...
  x << lambda { i }
end
# WAT
x.map(&:call) # [3, 3, 3]

x = []
(1..3).each { |i| x << lambda { i } }
# sanity restored
x.map(&:call) # [1, 2, 3]

Using my hack above to make your for act more like an each makes already confusing behavior even more confusing. Better to avoid for entirely.

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

2 Comments

Thank you @Max, your example with proc answers my question. I agree that it is not a nice structure to see. On the other side, for is (with if) the most written word in computer programming, it is a pity to leave it out of business in Ruby.
@NicolaMingotti I haven't written a single for loop outside of experiments like this in all my years of using Ruby. I'm pretty sure it's only in there so that people don't freak out when they come over from other languages.
0

I don't think that is possible, for loops do not have a scope of their own.

Comments

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.