Ruby on Rails序列化哈希对象

时间:2011-12-27 16:19:43

标签: ruby-on-rails ruby-on-rails-3 serialization

如何在Ruby on Rails中将此哈希序列化为此字符串?

谢谢!

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

2 个答案:

答案 0 :(得分:1)

我仍然不能完全相信你在这里做的是正确的事情,但只是回答你的问题:

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

答案 1 :(得分:0)

您也可以使用YAML或JSON序列化它。

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

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

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

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