Ruby: Creating a hash key and value from a variable in Ruby [duplicate]

If you want to populate a new hash with certain values, you can pass them to Hash::[]:

Hash["a", 100, "b", 200]             #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ]   #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200]         #=> {"a"=>100, "b"=>200}

So in your case:

Hash[id, 'foo']
Hash[[[id, 'foo']]]
Hash[id => 'foo']

The last syntax id => 'foo' can also be used with {}:

{ id => 'foo' }

Otherwise, if the hash already exists, use Hash#=[]:

h = {}
h[id] = 'foo'