Normalize Input Parameters By Symbolizing Keys And Stripping Empty Strings In Ruby
When working with user-submitted forms or API input, it’s common to receive params with string keys and empty string values.
Description
This method demonstrates how to clean up that input by symbolizing keys and converting blank strings to nil
. It efficiently transforms a hash of parameters by:
- Preserving non-empty values without any unnecessary changes
- Replacing empty string values (
""
) withnil
to standardize missing input - Symbolizing all keys using
transform_keys(&:to_sym)
This is particularly useful in Rails applications when sanitizing input before using it in model validations, database inserts, or API payloads.
Sample input:input = { "name" => " John ", "email" => "", "active" => "true" }
Sample Output:{ name: " John ", email: nil, active: "true" }
Answer
def normalize_params(params)
params.transform_keys(&:to_sym).transform_values do |v|
v.is_a?(String) && v.strip.empty? ? nil : v
end
end
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs — boost your Personal Brand & career! 🚀