cgore.comcgore@cgore.commicroblogblogphotosChristianitycryptographyjournalingoutdoorsmy master's thesisprogramming
Thinking Bicycle
Github @cgoreFacebook @cgoreInstagram @christopher.mark.gore

This website is copyright © 1995-2016 Christopher Mark Gore, all rights reserved. The content may not be copied or republished via any means, traditional or electronic, without express written permission of the author.

Chris Gore: Programming: Ruby: Block-Local Variables

Here's a new feature in Ruby 1.9 versus Ruby 1.8: block-local variables. This is best shown with an example.

[[1,2],[3,4]].map {|x,y; t| t = x+y; t**2}

This returns [9, 49] which makes sense.

How is this different? Well, consider this slightly different version.

t = 42
[[1,2],[3,4]].map {|x,y| t = x+y; t**2}
u = t+43

The value of u is 50 in this case. It updates the existing variable from the outer scope. If you scope it locally, the value of u will instead be 85. This can be a tricky bug to catch, by the way.