Pedro Sturmer
Pedro Sturmer

Reputation: 594

How to collect many attributes from hash in ruby

I'm wondering if it's possible to collet many attributes from a hash.

Currently using ruby 2.6.3

Something like that

hash = { name: "Foo", email: "Bar", useless: nil }
other_hash = hash[:name, :email]

The output should be another hash but without the useless key/value

Upvotes: 2

Views: 1074

Answers (2)

iGian
iGian

Reputation: 11183

If useless keys are so for having nil values, you can also use Hash#compact:

h = { name: "Foo", email: "Bar", useless: nil }
h.compact #=> {:name=>"Foo", :email=>"Bar"}

Upvotes: 3

Sebastián Palma
Sebastián Palma

Reputation: 33420

You can use Ruby's built in Hash#slice:

hash = { name: "Foo", email: "Bar", useless: nil }
p hash.slice(:name, :email)
# {:name=>"Foo", :email=>"Bar"}

If using Rails you can use Hash#except which receives just the keys you want to omit:

p hash.except(:useless)
# {:name=>"Foo", :email=>"Bar"}

Upvotes: 7

Related Questions