0

我搜索了很多,但我现在很难过。我希望简化一个数组,这样使用起来会更容易一些......

现在我的数组看起来像这样:

[[{"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

任何帮助,将不胜感激。谢谢看!!

4

2 回答 2

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/cmap块可以采用多个参数,这些参数按数组的索引顺序分配。所以map遍历a数组,取出每个散列和内容字符串。然后我们将内容字符串分配给散列的新content成员并返回散列。

于 2013-11-06T00:04:13.437 回答
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]}表达式显示值。

于 2013-11-06T00:24:12.483 回答