检查并 select 哈希数组中的最新一个
Check and select the latest one from the array of hashes
我必须检查 select 哈希数组中的最新一个。结构是这样的:
'histories':[
{
{
...
},
'created': "date1",
'items':[
{
'a': "Ready",
'b': "dfknsknfs",
},
{
'a': "sdfjbsf",
'b': "hello23",
}
]
},
{
{
...
},
'created': "date2",
'items':[
{
'a': "sknfkssd",
'b': "ksdfjshs",
},
{
'a': "Ready",
'b': "shdfjsh",
}
]
},
...
]
我必须先找到值 "Ready",然后我必须 select 最新的 "created" 日期。
我的尝试是这样的
ready_item = histories.select { |item| item.items.detect {|f| f.a == "Ready" } }
ready_item
但由于使用了 detect
,它只返回第一个检测到的值。但我需要得到最新的日期。它的可能解决方案应该是什么?
我已经或多或少地使散列成为垃圾,如果我正确理解了要求,请开始:
hash = { histories:[
{ created: "2014-04-01",
items:[
{ a: "Ready", b: "NOT to be chosen" },
{ a: "sdfjbsf", b: "hello23" }
]},
{ created: "2015-04-01",
items:[
{ a: "Ready", b: "to be chosen" },
{ a: "sdfjbsf", b: "hello23" }
]},
{ created: "2014-03-01",
items:[
{ a: "sknfkssd", b: "ksdfjshs" },
{ a: "unready", b: "shdfjsh" }
]}
]}
hash[:histories].select do |item|
item[:items].detect do |item|
item[:a] == 'Ready' # select ready only
end
end.reduce(nil) do |memo, item| # reduce to newest
memo = item if memo.nil? ||
Date.parse(memo[:created]) < Date.parse(item[:created])
end
#⇒ {
# :created => "2015-04-01",
# :items => [
# [0] {
# :a => "Ready",
# :b => "to be chosen"
# },
# [1] {
# :a => "sdfjbsf",
# :b => "hello23"
# }
# ]
# }
histories.select { |h|
h[:items].detect {|f| f[:a] == 'Ready' }
}.sort_by {|x| x[:created_at] }.last
我必须检查 select 哈希数组中的最新一个。结构是这样的:
'histories':[
{
{
...
},
'created': "date1",
'items':[
{
'a': "Ready",
'b': "dfknsknfs",
},
{
'a': "sdfjbsf",
'b': "hello23",
}
]
},
{
{
...
},
'created': "date2",
'items':[
{
'a': "sknfkssd",
'b': "ksdfjshs",
},
{
'a': "Ready",
'b': "shdfjsh",
}
]
},
...
]
我必须先找到值 "Ready",然后我必须 select 最新的 "created" 日期。
我的尝试是这样的
ready_item = histories.select { |item| item.items.detect {|f| f.a == "Ready" } }
ready_item
但由于使用了 detect
,它只返回第一个检测到的值。但我需要得到最新的日期。它的可能解决方案应该是什么?
我已经或多或少地使散列成为垃圾,如果我正确理解了要求,请开始:
hash = { histories:[
{ created: "2014-04-01",
items:[
{ a: "Ready", b: "NOT to be chosen" },
{ a: "sdfjbsf", b: "hello23" }
]},
{ created: "2015-04-01",
items:[
{ a: "Ready", b: "to be chosen" },
{ a: "sdfjbsf", b: "hello23" }
]},
{ created: "2014-03-01",
items:[
{ a: "sknfkssd", b: "ksdfjshs" },
{ a: "unready", b: "shdfjsh" }
]}
]}
hash[:histories].select do |item|
item[:items].detect do |item|
item[:a] == 'Ready' # select ready only
end
end.reduce(nil) do |memo, item| # reduce to newest
memo = item if memo.nil? ||
Date.parse(memo[:created]) < Date.parse(item[:created])
end
#⇒ {
# :created => "2015-04-01",
# :items => [
# [0] {
# :a => "Ready",
# :b => "to be chosen"
# },
# [1] {
# :a => "sdfjbsf",
# :b => "hello23"
# }
# ]
# }
histories.select { |h|
h[:items].detect {|f| f[:a] == 'Ready' }
}.sort_by {|x| x[:created_at] }.last