Ruby: Creating a hash key and value from a variable in Ruby

RubyHashSyntax

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames McMahonView Question on Stackoverflow
Solution 1 - RubyGumboView Answer on Stackoverflow