Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - getting value of hash

I have a hash like

{:key1 => "value1", :key2 => "value2"}

And I have a variable k which will have the value as 'key1' or 'key2'.

I want to get the value of k into a variable v.

Is there any way to achieve this with out using if or case? A single line solution is preferred. Please help.

like image 404
Sayuj Avatar asked Dec 30 '11 05:12

Sayuj


People also ask

How do I get the hash value in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do I get the hash key?

Simply pressing alt and 3 at the same time will insert a # hash symbol into your text in any application. This shortcut will work with all versions of Mac OS X whether you have a Macbook, Air or an iMac. In most cases Apple has decided to replace this key with a symbol of the local currency.

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

What does hash do in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


1 Answers

Convert the key from a string to a symbol, and do a lookup in the hash.

hash = {:key1 => "value1", :key2 => "value2"} k = 'key1'  hash[k.to_sym] # or iow, hash[:key1], which will return "value1" 

Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases. I know that you've only tagged your question with Ruby, but you could steal the implementation of this class from Rails' source to avoid string to symbol and symbol to string conversions throughout your codebase. It makes the value accessible by using a symbol or a string as a key.

hash = HashWithIndifferentAccess.new({:key1 => "value1", :key2 => "value2"}) hash[:key1]  # "value1" hash['key1'] # "value1" 
like image 81
Anurag Avatar answered Oct 03 '22 01:10

Anurag