我搜索了很多,但目前我很难过。我希望简化一个数组,以便更容易使用......
现在我的数组看起来像这样:
[[{"title"=>"Test Entry 2", "date"=>"2013-11-01 21:05"}, "\nThis is just another test entry."], [{"title"=>"Test Entry", "date"=>"2013-11-01 18:05"}, "\nThis is just a test entry."]]
要打印我目前拥有的这些值:
entries.each do |x|
puts x[0]["title"]
puts x[0]["date"]
puts x[1]
end
我希望它看起来像这样(我想):
[{"title"=>"Test Entry 2", "date"=>"2013-11-01 21:05", "content"=>"\nThis is just another test entry".}], [{"title"=>"Test Entry", "date"=>"2013-11-01 18:05", "content"="\nThis is just a test entry.}]
我希望能够通过循环轻松调用这些值,例如:
entries.each do |entry|
puts entry["title"]
puts entry["date"]
puts entry["content"]
end
任何帮助将不胜感激。谢谢你的期待!!
答案 0 :(得分:0)
怎么样
a = [[{"title"=>"Test Entry 2", "date"=>"2013-11-01 21:05"}, "\nThis is just another test entry."], [{"title"=>"Test Entry", "date"=>"2013-11-01 18:05"}, "\nThis is just a test entry."]]
a.map! {|hsh, content| hsh['content'] = content; hsh }
#=> [{"title"=>"Test Entry 2", "date"=>"2013-11-01 21:05", "content"=>"\nThis is just another test entry."}, {"title"=>"Test Entry", "date"=>"2013-11-01 18:05", "content"=>"\nThis is just a test entry."}]
这适用于b / c map
块可以采用以数组的索引顺序分配的多个参数。因此map
遍历a
数组,拉出每个哈希和内容字符串。然后,我们将内容字符串分配给散列的新content
成员并返回散列。
答案 1 :(得分:0)
你已经做到了。在纠正了一个小错误后,你正在追踪
entries=[
{"title"=>"Test Entry 2", "date"=>"2013-11-01 21:05", "content"=>"\nThis is just another test entry."},
{"title"=>"Test Entry", "date"=>"2013-11-01 18:05", "content"=>"\nThis is just a test entry."}
]
entries.each do |entry|
puts entry["title"] # Test Entry 2
puts entry["date"] # 2013-11-01 21:05
puts entry["content"] #
# This is just another test entry.
end
只是一个哈希数组。您还可以使用entry.keys.each {|k| puts entry[k]}
表达式显示值。