Double use of the same variable

I see examples that look like this:

str = String.build do |str|
  str << "hello "
  str << 1
end
str # => "hello 1"

where the same variable name appears in two different uses. The above for example would also work this way as the internal “str” variable has nothing to do with the external one.

str = String.build do |temp|
  temp << "hello "
  temp << 1
end
puts str # => "hello 1"

At first it was very confusing to me because I did not understand why do we need to both assign to the str in the first line and use it as a loop variable.
Now it is just confusing.

I wonder if this is really a good idea to use the same variable name internally as externally in these constructs? Is this how you also write in your real code?

This is definitely not a good idea and a code smell. ameba complains about shadowing an outer local variable.

Maybe the compiler should’ve prevented that in the first place. But on the other hand, I think it’s formally pretty straight and clearly separated by the scopes. Just us humans are confused by the same label having different meanings.

1 Like

The first versions of the language disallowed this but many of us found it to be very restrictive or annoying. str refers to a same concept here: either the string being built it tbe string fully built. I think using a same name is easier and more intuitive. Having to use two names, and specially having to come up with these names, is pretty annoying and distracting. At least that’s my opinion. And it works the same way in Ruby.

2 Likes

I agree that coming up with two names would be difficult :slight_smile:

Well, I always use io as name for the block argument to String.build:thinking:

3 Likes