Assigning a variable on the same line as a hash returning from a method in ruby

I have a method that returns the hash map { :name => "Test", :desc => "Test Description } . It will always return :name and :description .

How can I assign 2 variables in the returned hash.

I could do this, but it will call the method twice:

 @name, @desc = get_name_desc_map[:name], get_name_desc_map[:desc] 

I want to call the method only once.

+6
source share
1 answer

It is very simple to use a parallel Ruby assignment:

 @name, @desc = get_name_desc_map.values 

Another way (if you don't know the order of the keys in the original hash):

 @name, @desc = get_name_desc_map.values_at(:name, :desc) 

Hash#values_at and Hash#values .

+13
source

All Articles