Rubyオブジェクトをテキストで保存する3つの方法
DBに保存したいときなどに利用。IOやProcオブジェクトには使えません。
また、それぞれの方法でrequireしているライブラリがありますが、Rails内であればbase64もyamlも、もちろんactive_supportもあらかじめロードされています。
Marshalとbase64の組み合わせ
require 'base64' foo = {"name"=>"toyoshi","age"=>"16"} text = Base64.encode64(Marshal.dump(foo)) #=> "BAh7ByIJbmFtZSIMdG95b3NoaSIIYWdlIgcxNg==\n" Marshal.load(Base64.decode64(text)) #=> {"name"=>"toyoshi", "age"=>"16"}
YAMLを使う
require 'yaml' foo = {"name"=>"toyoshi","age"=>"16"} text = foo.to_yaml #=> "--- \nname: toyoshi\nage: \"16\"\n" YAML.load(text) #=> {"name"=>"toyoshi", "age"=>"16"}
jsonを使う
require 'rubygems' require 'active_support' foo = {"name"=>"toyoshi","age"=>"16"} text = foo.to_json #=> "{\"name\":\"toyoshi\",\"age\":\"16\"}" ActiveSupport::JSON.decode(text) #=> {"name"=>"toyoshi", "age"=>"16"}