看板 Ruby 關於我們 聯絡資訊
其實問題沒有這麼複雜 ActiveSupport::JSON.decode 的動作很直接 會把原文中的 foo_json 解成一個 Array of Hash gotfat 兄所提到的 attributes= 是為了要一次設定很多個 attr 才需要的 這個例子中只有一個 @value 的話,就直接把 hash 中的值取出來就好了 ActiveSupport::JSON.decode(foo_json).inject([]){ |result, foo_attrs| result << Foo.new(foo_attrs['value']) } 如果要用 attributes= 來設定很多的 attr,那要改寫一下: class Foo attr_accessor :value1, :value2 def initialize(hash) self.attributes = hash end def attributes=(hash) hash.each do |k,v| instance_variable_set("@#{k}".to_sym, v) end end end foo_arr = [] foo_arr << Foo.new(:value1 => 1, :value2 =>2) foo_arr << Foo.new('value1' => 10.5, :value2 => 'string') foo_json = foo_arr.to_json ActiveSupport::JSON.decode(foo_json).inject([]){ |result, foo_attrs| result << Foo.new(foo_attrs) } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.70.236
suomax:太棒了!感謝!:D 10/05 17:43