Why do I need to use #{}


#1



https://www.codecademy.com/courses/ruby-beginner-en-F3loB/2/4?curriculum_id=5059f8619189a5000201fbcb#


I just don't understand why I have to use "#{item1}: #{item2}" instead of being able to use item1 + ": " + item2


secret_identities.each do |value1, value2|
    puts "#{value1}: #{value2}"
end

secret_identities.each do |value1, value2|
    puts value1 + ": " + value2
end


#2

I think the real question is what "have to" means here, there are differences between:
- two equivalent actions
- two differing actions having the same effect
- two differing actions having different effects
So which scenario are you asking about, and what's stopping you from using the other action?


#3

The second one is giving me a syntax error about an undefined local variable. My question I guess is doesn't having |value1, value2| technically make them local variables for that loop?


#4

It does, which means you changed something else or you weren't getting that error message at all

$ cat tekkie.rb   # show the code I'm running
secret_identities = {'bob' => 'notbob'}

secret_identities.each do |value1, value2|
    puts "#{value1}: #{value2}"
end

secret_identities.each do |value1, value2|
    puts value1 + ": " + value2
end



$ ruby tekkie.rb  # showing that both have the same effect in this case
bob: notbob
bob: notbob

#5

Hmm, that's strange. I went back and tried it again and now both methods are working now. Not sure why it wasn't before. Thanks.


#6

Note that they are not equivalent though. What happens if the hash has numbers as keys and/or values?


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.