ruby

Local variables in Ruby blocks

One thing while using iterators is that they can use the local variables defined already thereby altering them.

see this code :

a = 10
(1..5).each { |a| p a }
p a   # => 5

see here that although we expected the ‘a’ inside the iterator to be different than the ‘a’ outside yet it modified the outside ‘a’.

Although the same functionality can help you sometimes too.

see this code :

a = 10
(1..5).each { |b| p a+b }
p a

here we are utilizing the fact that we can use local variables inside the iterator and are using them.

Use iterators cautiously !

Advertisements

One thought on “Local variables in Ruby blocks

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s