In PHP it's very common to use a variable as an associative array key:
$keys = array('mykey', 'another_key');
$array = array();
foreach ($keys AS $key) { $array[$key] = "hello world\n"; }
foreach ($keys AS $key) { echo $array[$key]; }
>> hello world
hello world
In Ruby, the presence (and use of Symbols) makes this a bit tricky:
keys = ['mykey', 'another_key']
myarray = { :mykey => 'hello world', 'another_key' => 'goodbye world' }
myarray.each { |k|
puts myarray[k]
}
>> hello world
goodbye world
Now if we try this again using instead the Strings from the keys array we get a different result:
keys.each { |k|
puts myarray[k]
}
>>
goodbye world
We don't get the first array value back because a String key is not the same as a Symbol key, even if they consist of the same sequence of characters. This is one of the gotchyas with Ruby.
In Ruby the 'value of a Symbol is not the same as that of a String. So :key != "key". From an ease of use perspective it would be convenient if they did.
Thankfully the language stewards saw fit to include String.to_sym as a convenience method to create a Symbol from a String's value.
keys.each { |k|
puts myarray[k.to_sym]
}
>> hello world