0

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'}"
2
  • Why do you want this? It seems like you're trying to do something fishy without providing all of the details, and usually there's a better way to accomplish whatever you're trying to do Commented Dec 27, 2011 at 16:22
  • i have to load mercury snippets like this: Mercury.Snippet.load({ snippet_1: {name: 'example', options: {'options[favorite_beer]': "Bells Hopslam", 'options[first_name]': "Jeremy"}} }); and have a serialized object of options available Commented Dec 27, 2011 at 16:24

2 Answers 2

1

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'}"
Sign up to request clarification or add additional context in comments.

Comments

0

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\"}}" 

1 Comment

Ah, sorry, didn't see it was particularly for Mercury. Yeah, you'll have to use a custom method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.