【问题标题】:Sort Nested Hash Inside Array对数组内的嵌套哈希进行排序
【发布时间】:2014-08-06 13:41:44
【问题描述】:

我有这样的示例数据:

[
  [{"calendar"=>{:start_date=>Thu, 07 Aug 2014, :title=>"Recurring Event Test", :has_downloads=>false, :description=>"<p>Recurring content</p>\r\n", :location=>"Lunch hall", :id=>243, :end_date=>Thu, 07 Aug 2014}}],
  [{"calendar"=>{:start_date=>Wed, 06 Aug 2014, :title=>"Single event", :has_downloads=>false, :description=>"<p>for date 6th</p>\r\n", :location=>"chennai", :id=>253, :end_date=>Wed, 06 Aug 2014}}] 
]

需要按start_date 字段排序这些值。

我试过这样

sort_by {|vn| vn[:start_date]} 

它显示错误 nil 类

【问题讨论】:

  • 您已经尝试过什么,可能是在查看了各种sort methods of arrays 之后?请向我们展示代码。你的方法有什么问题?
  • 你为什么打电话给:datetime
  • 你有一个数组数组,所以做类似sort_by {|x| x.first[:start_date]}
  • @Grych 收到此错误 Symbol as array index - (TypeError)

标签: ruby-on-rails ruby arrays sorting


【解决方案1】:

vn 是一个数组,start_date 嵌套在 calendar 中。你应该这样做

arr.sort_by {|vn| vn[0]["calendar"][:start_date]}

【讨论】:

  • 你的旧答案只能工作... arr.sort_by {|vn| vn["日历"][:start_date]}
  • 在您的问题中,您有一个数组数组。如果我之前的答案有效,那么您可能有一个哈希数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多