Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

hash

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.

like image 766
James McMahon Avatar asked Jan 29 '14 19:01

James McMahon


People also ask

Can a hash have duplicate keys Ruby?

Short answer is no, hashes need to have unique keys.

How do you make hash hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.

How do you add a value to a hash in Ruby?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.

Can a hash have multiple values Ruby?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.


1 Answers

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' 
like image 142
Gumbo Avatar answered Oct 05 '22 00:10

Gumbo