3 ms·
> If it gets block scope (which Ruby also doesn't really have, I think?) Yeah, it does, but it's a little different. Here I iterate through an array in a block
by compay 18y ago
> If it gets block scope (which Ruby also doesn't really have, I think?)
Yeah, it does, but it's a little different. Here I iterate through an array in a block, assigning the current value to a local variable. Afterwards you can see that local_var remains undefind in the higher scope.
[norman@elis] +> irb
>> [1, 2, 3].each {|i| local_var = i; puts local_var}
1
2
3
=> [1, 2, 3]
>> puts local_var
NameError: undefined local variable or method `local_var'
for main:Object
from (irb):2
from :0
>>
However unlike C-like languages, Ruby doesn't treat if/else type statements as a block. So for example this works in Ruby:
>> if true
>> local_var = "hello"
>> end
=> "hello"
>> puts local_var
hello