/ Tags: RAILS-CODE / Categories: SOLUTIONS

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 ("") with nil 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

Learn More

cdrrazan

Rajan Bhattarai

Software Engineer by work! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More