Kieran Klaassen
Kieran Klaassen

Reputation: 2202

Ruby on Rails Serialize hash object

how can I serialize this hash to this string in Ruby on Rails?

Thanks!

{"options"=>{"first_name"=>"Jeremy", "favorite_beer"=>"Bells Hopslam"}} =>
"{'options[favorite_beer]': 'Bells Hopslam', 'options[first_name]': 'Jeremy'}"

Upvotes: 0

Views: 2392

Answers (2)

hurshagrawal
hurshagrawal

Reputation: 673

You can also serialize it in YAML or JSON.

{"options"=>{"first_name"=>"Jeremy", "favorite_beer"=>"Bells Hopslam"}}.to_yaml =>

"--- \noptions: \n  first_name: Jeremy\n  favorite_beer: Bells Hopslam\n"

or

{"options"=>{"first_name"=>"Jeremy", "favorite_beer"=>"Bells Hopslam"}}.to_json =>

"{\"options\":{\"first_name\":\"Jeremy\",\"favorite_beer\":\"Bells Hopslam\"}}" 

Upvotes: 0

Lee Jarvis
Lee Jarvis

Reputation: 16241

I'm still not completely assured that you're doing the right thing here, but to just answer your question:

def stringify(hash)
  items = hash.map do |key, inner|
    inner.map { |k, v| "'#{key}[#{k}]': '#{v}'" }
  end

  "{#{items.join(', ')}}"
end


p stringify({"options"=>{"first_name"=>"Jeremy", "favorite_beer"=>"Bells Hopslam"}})
#=> "{'options[first_name]': 'Jeremy', 'options[favorite_beer]': 'Bells Hopslam'}"

Upvotes: 1

Related Questions