Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a hash key using a variable in Ruby 1.9?

Tags:

ruby

I have a variable that is a string. I want to create a hash using the variable as a key. In Ruby 1.8, I used the hashrocket syntax, like this:

my_key = 'arbitrary'
my_hash = {my_key => 'my_value'}

In Ruby 1.9, there is a new syntax and I can do this:

my_hash = {arbitrary: 'my_value'}

But how do I do convert the variable to a key? I tried:

my_key = 'arbitrary'
my_hash = {:my_key 'my_value'} 
my_hash = {my_key.to_sym: 'my_value'}
my_hash = {:my_key.to_sym 'my_value'} 
my_hash = {my_key.to_sym 'my_value'}

Do I have to continue to use the Ruby 1.8 syntax?

like image 657
Daniel Kehoe Avatar asked Jul 19 '26 09:07

Daniel Kehoe


2 Answers

Let me introduce you two ways to do what you exactly want. If you don't want to continue using 1.8 syntax and hashrockets anymore, ruby-doc.org recommends doing it in this way in Ruby 1.9.3:

my_hash = Hash.new

my_key = "key000"
my_hash[my_key] = "my_value"

Livedemo: http://ideone.com/yqIx2M

Second one (more similar to what you are trying to achieve) is:

my_key = "key0"
my_hash = Hash[my_key, "value00"]

puts my_hash

Livedemo: http://ideone.com/HHLyAi

like image 96
mtszkw Avatar answered Jul 21 '26 21:07

mtszkw


{arbitrary: 'my_value'} is syntactic sugar for {:arbitrary => 'my_value'}, and :arbitrary is syntactic sugar for 'arbitrary'.to_sym(yes, this is a lie, since :arbitrary interns when the interpreter reads the code and 'arbitrary'.to_sym interns when it executes the code, but for the sake of the explanation let's pretend they're equivalent)

So, {arbitrary: 'my_value'} can be written as {'arbitrary'.to_sym => 'my_value'}, and since you have the key in a variable, you can use:

my_key = 'arbitrary'
my_hash = {my_key.to_sym => 'my_value'}

Keep in mind though that when you use to_sym you are risking creating lots of symbols, which will stay in memory forever(ish), so you might want to consider using string-keys with your old syntax. For more info about the difference between strings and symbols read this: http://www.randomhacks.net/2007/01/20/13-ways-of-looking-at-a-ruby-symbol/

like image 21
Idan Arye Avatar answered Jul 21 '26 22:07

Idan Arye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!