Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using constant as keys in ruby hash

Assuming I have 2 strings constants

KEY1 = "Hello"
KEY2 = "World"

I would like to create a hash using these constants as key values.

Trying something like this:

stories = {
  KEY1: { title: "The epic run" },
  KEY2: { title: "The epic fail" }
}

Doesn't seem to work

stories.inspect
#=> "{:KEY1=>{:title=>\"The epic run\"}, :KEY2=>{:title=>\"The epic fail\"}}"

and stories[KEY1] obviously doesn't work.

like image 557
Maxim Veksler Avatar asked Nov 09 '16 10:11

Maxim Veksler


People also ask

How do I add a key 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.

What can be a hash key in Ruby?

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

Can a Ruby hash key be an integer?

Hashes use keys to identify values, A key can be almost any object (String, Integer, Symbol, Object)


1 Answers

KEY1: is the syntax sugar to :KEY1 =>, so you're actually having symbol as key, not constant.

To have actual object as a key, use hash rocket notation:

stories = {
  KEY1 => { title: "The epic run" },
  KEY2 => { title: "The epic fail" }
}
stories[KEY1]
#=> {:title=>"The epic run"}
like image 103
Andrey Deineko Avatar answered Sep 16 '22 15:09

Andrey Deineko