Anthony Deluca Anthony Deluca - 1 year ago 39
Ruby Question

Using to assign hash values inside a loop. I can't explain the following output


letter = "a"
chars =

for i in 1..5
chars[i] = letter
puts letter!

puts chars

=== Output:






{1=>"f", 2=>"f", 3=>"f", 4=>"f", 5=>"f"}

=== Question

I don't understand why I don't get
{1=>"a" , 2=>"b" , 3=>"c", 4=>"d" , 5=>"e" }

I included the puts statement to check that at each stage of the iteration the letter is correct.

Thanks in advance.

Answer Source

chars[i] = letter doesn't assign a copy of letter to chars[i]. letter is a reference to string "a" and it assigns that reference to chars[i]. So after you assign char[1] = letter, then change letter with!, char[1] now refers to the same, new value of the string that letter does. See Ruby: how can I copy a variable without pointing to the same object?, and change your code to:

for i in 1..5
    chars[i] = letter.dup   # Assign a copy of `letter` to chars[i]
    puts letter!