jeudi 10 avril 2014

affectation d'une variable multiples en une seule ligne avec le hachage de retour de la méthode en ruby - Stack Overflow


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.




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 .



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.



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 .


0 commentaires:

Enregistrer un commentaire