Something like let in Ruby

后端 未结 2 1485
情书的邮戳
情书的邮戳 2021-01-21 14:18

I used to write let-like expressions -- with lexical scope.

So I write my own (sad, but it will fail with multiple threads):

# Useful thing for replacing         


        
2条回答
  •  别那么骄傲
    2021-01-21 14:50

    You can't specify the value that you want to initialize, but you can declare a variable as explicitly local to that block:

    x = 'external value'
    puts x
    [1,2,3].each do |i; x|
      x = i
      puts x
    end
    puts x
    

    This will result in:

    external value
    1
    2
    3
    external value
    

提交回复
热议问题