This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Extracting Portions of Hashes (written by Ben Giddings)
CodeExpectedActual
require 'time'
click_counts = {}
1.upto(30) { |i| click_counts[Time.parse("2006-09-#{i}")] = 400 + rand(700) }
p click_counts
{Sat Sep 23 00:00:00 EDT 2006=>803, Tue Sep 12 00:00:00 EDT 2006=>829,
Fri Sep 01 00:00:00 EDT 2006=>995, Mon Sep 25 00:00:00 EDT 2006=>587,
...
{Sat Sep 23 00:00:00 EDT 2006=>803, Tue Sep 12 00:00:00 EDT 2006=>829, Fri Sep 01 00:00:00 EDT 2006=>995, Mon Sep 25 00:00:00 EDT 2006=>587, Thu Sep 14 00:00:00 EDT 2006=>449, Sun Sep 03 00:00:00 EDT 2006=>888, Wed Sep 27 00:00:00 EDT 2006=>948, Sat Sep 16 00:00:00 EDT 2006=>592, Tue Sep 05 00:00:00 EDT 2006=>637, Fri Sep 29 00:00:00 EDT 2006=>1083, Mon Sep 18 00:00:00 EDT 2006=>933, Thu Sep 07 00:00:00 EDT 2006=>747, Wed Sep 20 00:00:00 EDT 2006=>697, Sat Sep 09 00:00:00 EDT 2006=>1002, Fri Sep 22 00:00:00 EDT 2006=>457, Mon Sep 11 00:00:00 EDT 2006=>406, Sun Sep 24 00:00:00 EDT 2006=>817, Wed Sep 13 00:00:00 EDT 2006=>924, Sat Sep 02 00:00:00 EDT 2006=>440, Tue Sep 26 00:00:00 EDT 2006=>951, Fri Sep 15 00:00:00 EDT 2006=>859, Mon Sep 04 00:00:00 EDT 2006=>431, Thu Sep 28 00:00:00 EDT 2006=>977, Sun Sep 17 00:00:00 EDT 2006=>412, Wed Sep 06 00:00:00 EDT 2006=>860, Sat Sep 30 00:00:00 EDT 2006=>415, Tue Sep 19 00:00:00 EDT 2006=>960, Fri Sep 08 00:00:00 EDT 2006=>439, Thu Sep 21 00:00:00 EDT 2006=>991, Sun Sep 10 00:00:00 EDT 2006=>1065}
low_click_days = click_counts.select {|key, value| value < 450 }
[[Thu Sep 14 00:00:00 EDT 2006, 449], [Mon Sep 11 00:00:00 EDT 2006, 406],
[Sat Sep 02 00:00:00 EDT 2006, 440], [Mon Sep 04 00:00:00 EDT 2006, 431],
...
low_click_days_hash = click_counts.inject({}) do |h, kv|
  k, v = kv
  h[k] = v if v < 450
  h
end
{Mon Sep 25 00:00:00 EDT 2006=>403, {Thu Sep 14 00:00:00 EDT 2006=>449, Mon Sep 11 00:00:00 EDT 2006=>406, Sat Sep 02 00:00:00 EDT 2006=>440, Mon Sep 04 00:00:00 EDT 2006=>431, Sun Sep 17 00:00:00 EDT 2006=>412, Fri Sep 08 00:00:00 EDT 2006=>439, Sat Sep 30 00:00:00 EDT 2006=>415}
low_click_days_hash = Hash[*low_click_days.flatten]
{Thu Sep 14 00:00:00 EDT 2006=>449, Mon Sep 11 00:00:00 EDT 2006=>406, {Thu Sep 14 00:00:00 EDT 2006=>449, Mon Sep 11 00:00:00 EDT 2006=>406, Sat Sep 02 00:00:00 EDT 2006=>440, Mon Sep 04 00:00:00 EDT 2006=>431, Sun Sep 17 00:00:00 EDT 2006=>412, Fri Sep 08 00:00:00 EDT 2006=>439, Sat Sep 30 00:00:00 EDT 2006=>415}