如何将字符串转换为数组哈希?

时间:2014-08-25 16:49:06

标签: ruby-on-rails ruby arrays

如何将此字符串(它是db中的一个字符串)转换为数组哈希?

---
fl:
- 
- 500.0
price:
- 2162.72
- 2152.72
period:
- 
- 3 weeks

我通过这样做获得了这些数据:

changes_data = box.changes.to_hash
changes_data.each do |key, val|
  if val[0].eql? val[1]
    changes_data.delete(key)
  else
    changes_data[key] = val.to_a
  end
end

但现在我不知道如何转换回来。 我想要得到这个:

{:fl => ['0', '500.0'], :price=>['2162.72','2152.72'],.......}

或转换为对象box

1 个答案:

答案 0 :(得分:1)

看起来您的数据只是YAML。所以你可以这样做:

require 'yaml'

serialized_str = ... # retrieve the serialized string from the database
deserialized_hash = YAML.parse(serialized_str).to_ruby

deserialized_hash.class # => Hash

Ruby Docs