Junaid Farooq
Junaid Farooq

Reputation: 2608

removing a value from hash if key matches rails

I have seen many answers as removing any key which has value of nil or "", But this is not what i want.

I have a hash like this

{"firstname"=>"Jie",
 "lastname"=>"Pton",
 "email"=>"[email protected]",
 "country_id"=>"1",
 "payment_method"=>"0",
 "insight_id"=>"",
 "password"=>""}

And I only want to remove the password attribute from hash if its empty, NOT ALL which are empty

Upvotes: 3

Views: 1481

Answers (4)

Neeraj Kumar
Neeraj Kumar

Reputation: 1

You can use:

hash.reject{|k,v| k == 'password' && (v.nil? || v.empty?)}

or if you want to remove "password" key from original hash you can use "!"

eg. hash.reject!{|k,v| k == 'password' && (v.nil? || v.empty?)}

Upvotes: 0

Uday kumar das
Uday kumar das

Reputation: 1613

You can also use this solution:

hash.reject { |k,v| v.nil? || v.empty? }

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

More generic solution: for the hash given as an input (I assume it’s params, so let’s call it params) and the list of fields to be removed when empty:

TO_REMOVE_EMPTY = %w|password|
params.delete_if { |k, v| TO_REMOVE_EMPTY.include?(k) && v.empty? }

Upvotes: 4

unkmas
unkmas

Reputation: 987

hash.delete('password') if hash['password'].blank?

Upvotes: 1

Related Questions