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

TantrajJa
  • 1,987
  • 2
  • 15
  • 9

1 Answers1

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.

Community
  • 1
  • 1
niculare
  • 3,629
  • 1
  • 25
  • 39