In Ruby, when you assign a variable (in your case, it is d ) anywhere in the If-statement False branch, it declares this variable if the d= method is not defined. Basically b = bla-bla-bla in False-branch does this: b = nil .
When you use a block in an empty array, nothing happens. And if the array is not empty, the variable is still local to the current iteration of the block, unless the outer region of the block is defined, for example:
[1,2,3,4].each do |i| a=i end puts a
NameError: undefined local variable or `a 'method for main: Object
a=1 [1,2,3,4].each do |i| a=i end puts a
4
Also, you have the option to use a as local inside the block, if it was previously defined:
a=1 [1,2,3,4].each do |i; a| a=i end puts a
1
source share