Reputation: 2608
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
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
Reputation: 1613
You can also use this solution:
hash.reject { |k,v| v.nil? || v.empty? }
Upvotes: 0
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