Remove the key from the hash on Ruby/Rails and return only the remaining hash

Asked 1 years ago, Updated 1 years ago, 99 views

After removing the key from the hash on Ruby/Rails, how can I get only the remaining hash returned?

To add a new hash

{:a => 1, :b => 2}.merge!({:c => 3})   # => {:a=>1, :b=>2, :c=>3}

The hash is added like this, and the hash is returned, so what should I do to remove it? I can do it using reject, but I want something more intuitive.

{:a=> 1, :b=> 2}.reject!{ |k|k==:a} #Not this one
{:a => 1, :b => 2}.delete!(:a) # Like this

If possible, I'd like to have a single line of transmission of the factor. Is it my greed?

hashmap ruby ruby-on-rails

2022-09-22 22:09

1 Answers

Rails already has the exception/exception! method.

except(*keys) :

Returns a hash that includes everything but the given keys.

Return hash except key

hash = { a: true, b: false, c: nil}
hash.except(:c) # => { a: true, b: false}
hash # => { a: true, b: false, c: nil}

except!(*keys) :

Replaces the hash without the given keys.

Replacement of hash except key

hash = { a: true, b: false, c: nil}
hash.except!(:c) # => { a: true, b: false}
hash # => { a: true, b: false }

#tapUse method

h = {:a => 1, :b => 2}
puts h.tap { |hs| hs.delete(:a) }


2022-09-22 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.