It's the possibility of having a dream come true that makes life interesting.
Ruby has many ways of iterating. Those who came to Ruby via Rails will no doubt be familiar with über-iterator #each. This article though is about a less familiar (at least in Rails) way of iterating: the humble loop.
This is the final exercise in this series on variable scope by Launch School. Consider the code below:
a = 7array = [1, 2, 3]def my_value(ary) ary.each do |b| a += b endendmy_value(array)puts a
a = 7array = [1, 2, 3]array.each do |a| a += 1endputs a
The above code sets up two variables initially. a points to the number ‘7’ and array points to a 3-element array [1, 2, 3].
More on Variable Scope Within a Block
array = [1, 2, 3]array.each do |element| a = elementendputs a
In the past 6 “What’s My Value?” exercises we’ve focused on variable scope within and without methods. Here we have a different scenario: a block.
a = 7array = [1, 2, 3]