Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning multiple variable in one line with the hash returning from the method in ruby

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

How can I assign 2 variables in with 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 only want to call the method once.

like image 585
ed1t Avatar asked Apr 04 '14 23:04

ed1t


1 Answers

Very simple using Ruby's parallel assignment :

@name, @desc = get_name_desc_map.values

Other way is ( If you don't know the order of keys in the original hash ) :

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

Hash#values_at and Hash#values .

like image 156
Arup Rakshit Avatar answered Sep 17 '22 18:09

Arup Rakshit