Block Scope for Local Variables

Variable assignment inside a block can have a surprising effect if you're not careful. The following code ought to find a nutrient in a list, such that the amount supplied (as indicated by the hash value) is at least 100%, but it doesn't work very well:

label = {'Folicin'=>106, 'Vitamin A'=>146, 'Thiamine'=>94}
label.each do |nutrient, percent|
  last_full_rda = nutrient if percent >= 100
end

puts last_full_rda  # error: "undefined local variable"

Since last_full_rda first appears within the do...end block associated with each, its scope is limited to that block. (Not all code enclosures have this property. We'll earn a more intimate understanding of blocks on Day 14.) Making an assignment to last_full_rda above ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.