2

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

3
  • What's the expected output that would have? An array? or a hash without the useless key-value? Commented Jul 10, 2019 at 18:32
  • a hash without the useless key-value. @SebastianPalma Commented Jul 10, 2019 at 18:32
  • There is detailed answer for this, with different options to choose from, regarding how to remove a key from hash and get the remaining hash. stackoverflow.com/questions/6227600/… Commented Jul 11, 2019 at 6:28

2 Answers 2

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"} 

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"} 
Sign up to request clarification or add additional context in comments.

Comments

3

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"} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.