Nicely (and Recursively) Stringify a Hash’s Keys and Values

in code


Works in Ruby on Rails versions >= 4 and in Ruby 2.5. This has really annoyed the shit out of me. I want to stringify keys and values individually, not turn an entire hash or array into a string.

def deep_stringify(object)
  case object
  when Hash
    object.transform_keys(&:to_s).transform_values { |val| deep_stringify val }
  when Array
    object.map { |val| deep_stringify val }
  else
    object.to_s
  end
end

Rabble.




Your email address will not be published. Required fields are marked *