Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fetch multiple hash values at once?

What is a shorter version of this?:

from = hash.fetch(:from) to = hash.fetch(:to) name = hash.fetch(:name) # etc 

Note the fetch, I want to raise an error if the key doesn't exist.

There must be shorter version of it, like:

from, to, name = hash.fetch(:from, :to, :name) # <-- imaginary won't work 

It is OK to use ActiveSupport if required.

like image 993
Dmytrii Nagirniak Avatar asked Jul 15 '13 04:07

Dmytrii Nagirniak


People also ask

Can hash have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

Can a key have multiple values ruby?

Multiple Values For One Key Words are unique, but they can have multiple values (definitions) associated with them. You can do this in Ruby!

What is hash fetch?

Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception. Syntax: Hash.fetch() Parameter: Hash values. Return: value from the hash for the given key.


1 Answers

Use Hash's values_at method:

from, to, name = hash.values_at(:from, :to, :name) 

This will return nil for any keys that don't exist in the hash.

like image 159
Dylan Markow Avatar answered Sep 20 '22 23:09

Dylan Markow