How to collect many attributes from hash in ruby

Ped*_*mer 2 ruby hash ruby-on-rails

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]
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*lma 7

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"}
Run Code Online (Sandbox Code Playgroud)

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"}
Run Code Online (Sandbox Code Playgroud)