1

我有一个数组:

array=[
{"name"=>"Henry Jones ", "Date"=>"2013-04-09 15:09:02", "Duration"=>"0:00:00", "Call Type"=>"Outgoing"},
{"name"=>"Barry Smith ", "Date"=>"2013-04-08 13:51:03", "Duration"=>"0:00:48", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-04 19:30:19", "Duration"=>"0:00:49", "Call Type"=>"Outgoing"},
{"name"=>"Alistair Morgan ", "Date"=>"2013-04-05 13:14:07", "Duration"=>"0:00:03", "Call Type"=>"Outgoing"}, 
{"name"=>"Quentin Blah", "Date"=>"2013-04-05 13:19:44", "Duration"=>"0:04:28", "Call Type"=>"Missed"}, 
{"name"=>"Quentin Blah", "Date"=>"2013-04-05 13:25:19", "Duration"=>"0:09:45", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-05 14:35:29", "Duration"=>"0:00:24", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-05 15:54:53", "Duration"=>"0:00:00", "Call Type"=>"Missed"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-06 16:21:20", "Duration"=>"0:00:47", "Call Type"=>"Outgoing"}
] 

我想 group_by 日期字符串的日期(例如“2013-04-06”)我可以通过使用 group_by 整个日期字符串array_of_hashes.group_by {|d| d["Date"] }但是这需要整个字符串。

我怎样才能在不包括时间的日期分组?TIA

4

2 回答 2

3

您快到了。由于日期和时间是用空格隔开的,所以可以用String#split把日期和时间分开,然后用Array#first得到日期:

array_of_hashes.group_by do |hash|
  hash['Date'].split.first
end

使用 IRB,您可以看到它是如何工作的:

$ irb
2.0.0p0 :001 > date = "2013-04-06 16:21:20"
 => "2013-04-06 16:21:20" 
2.0.0p0 :002 > date.split
 => ["2013-04-06", "16:21:20"] 
2.0.0p0 :003 > date.split.first
 => "2013-04-06" 
于 2013-04-26T21:23:38.010 回答
2

for 的值Date只是一个字符串。幸运的是,它是一个行为良好、宽度固定、可排序的字符串。前 10 个字符是我们想要的:

array=[
{"name"=>"Henry Jones ", "Date"=>"2013-04-09 15:09:02", "Duration"=>"0:00:00", "Call Type"=>"Outgoing"},
{"name"=>"Barry Smith ", "Date"=>"2013-04-08 13:51:03", "Duration"=>"0:00:48", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-04 19:30:19", "Duration"=>"0:00:49", "Call Type"=>"Outgoing"},
{"name"=>"Alistair Morgan ", "Date"=>"2013-04-05 13:14:07", "Duration"=>"0:00:03", "Call Type"=>"Outgoing"}, 
{"name"=>"Quentin Blah", "Date"=>"2013-04-05 13:19:44", "Duration"=>"0:04:28", "Call Type"=>"Missed"}, 
{"name"=>"Quentin Blah", "Date"=>"2013-04-05 13:25:19", "Duration"=>"0:09:45", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-05 14:35:29", "Duration"=>"0:00:24", "Call Type"=>"Incoming"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-05 15:54:53", "Duration"=>"0:00:00", "Call Type"=>"Missed"}, 
{"name"=>"Henry Jones ", "Date"=>"2013-04-06 16:21:20", "Duration"=>"0:00:47", "Call Type"=>"Outgoing"}
] 

p array.group_by{|call| call["Date"][0..9]}
于 2013-04-26T21:41:19.410 回答