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

Pedro Sturmer
  • 547
  • 6
  • 20
  • What's the expected output that would have? An array? or a hash without the useless key-value? – Sebastián Palma Jul 10 '19 at 18:32
  • a hash without the useless key-value. @SebastianPalma – Pedro Sturmer Jul 10 '19 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. https://stackoverflow.com/questions/6227600/how-to-remove-a-key-from-hash-and-get-the-remaining-hash-in-ruby-rails/39231096#39231096 – techdreams Jul 11 '19 at 06:28

2 Answers2

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"}
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
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"}
iGian
  • 11,023
  • 3
  • 21
  • 36