88

I have a variable id and I want to use it as a key in a hash so that the value assigned to the variable is used as key of the hash.

For instance, if I have the variable id = 1 the desired resulting hash would be { 1: 'foo' }.

I've tried creating the hash with,

{
  id: 'foo'
}

But that doesn't work, instead resulting in a hash with the symbol :id to 'foo'.

I could have sworn I've done this before but I am completely drawing a blank.

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
James McMahon
  • 48,506
  • 64
  • 207
  • 283

1 Answers1

145

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'
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 6
    I was confused with question itself, now this answer made me double confused. :( Could you tell me what was OP asking? – Arup Rakshit Jan 29 '14 at 19:54
  • 1
    @ArupRakshit OP wants to use the value of `id` as key. `{ id: 'foo' }` doesn’t work as `id: 'foo'` is equivalent to `:id => 'foo'`. – Gumbo Jan 29 '14 at 19:58
  • 4
    Ah so the old style hash syntax works, but not the new style. Thank you. – James McMahon Jan 29 '14 at 19:59
  • 1
    @James: The JavaScript style only works with a [limited set of symbols](http://stackoverflow.com/a/8675314/479863) and only works in Hash literals. You can't use the JavaScript style if the key not a symbol (with a limited format). – mu is too short Jan 29 '14 at 20:16
  • What's really cool is _mixing_ the styles: `x = :a; puts ({y: 3, x => 5})` – Ray Toal Sep 02 '18 at 20:29
  • 2
    in `Ecmascript 6` you can build hashes using `variables` like `a = {"a": 100}` and `b = {"b": 200}` then `{a, b}` will be `=> {"a": 100, "b": 200}` but I don't believe this feauture exist in ruby – Fabrizio Bertoglio Aug 01 '19 at 13:14
  • Also, If you want to use a **key** and **value** that are variables you can use: `MyHash = { id => foo, id2 => foo2 }` OR `MyHash = Hash[id, foo, id2, foo2]`. If only the **key** is a variable then use: `MyHash = { id => 'foo', id2 => 'foo2' }` OR `MyHash = Hash[id, 'foo', id2, 'foo2']` – Promise Preston Jun 20 '21 at 10:26
  • 1
    You can also write it with string interpolation: `h = { "#{id}" => 'foo' }` – pmrotule Aug 25 '21 at 07:32