0

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]}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.