Reputation: 2017
I am just starting in Ruby, I am facing the following issue.
ip_array = [1.1.1.1,2.2.2.2]
for i in 0..1
puts `ping #{ip_array[#{i}]}`
end
This gives me an error: unexpected IDENTIFIER, expecting ']'
however this works
ip_array = [1.1.1.1,2.2.2.2]
for i in 0..1
puts `ping #{ip_array[i]}`
end
Can someone explain this, I think think #{ip_array[#{i}]}
is more correct than #{ip_array[i]}
Upvotes: 0
Views: 94
Reputation: 3687
Actually the version #{ip_array[i]}
is the correct one because variables are substituted inside ruby strings using the syntax: #{<var_name>}
, as you can see here.
So you cannot use a hashtag ('#') inside a variable name, like you are trying in #{ip_array[#{i}]
since this marks the beginning of a new variable subsitution and the previous substitution is not finished yet.
#ip_array[i]
is only one variable substituted in the string not two variables.
Upvotes: 4