fork download
  1. class Hash
  2. alias orig_each each
  3. def each(kwd = nil, &block)
  4. begin
  5. __send__("each_#{kwd}", &block)
  6. rescue NoMethodError
  7. orig_each(&block)
  8. end
  9. end
  10. end
  11.  
  12. if __FILE__ == $0
  13. require 'test/unit'
  14. class EachTest < Test::Unit::TestCase
  15. def setup
  16. @h = {a: 1, b: 2, c: 3}
  17. end
  18. def test_each_key
  19. e = @h.each(:key)
  20. assert_instance_of(Enumerator, e)
  21. assert_equal(:a, e.next)
  22. assert_equal(:b, e.next)
  23. assert_equal(:c, e.next)
  24. ary = []
  25. @h.each(:key) do |key|
  26. ary << key
  27. end
  28. assert_equal([:a, :b, :c], ary)
  29. end
  30. def test_each_value
  31. e = @h.each(:value)
  32. assert_instance_of(Enumerator, e)
  33. assert_equal(1, e.next)
  34. assert_equal(2, e.next)
  35. assert_equal(3, e.next)
  36. ary = []
  37. @h.each(:value) do |value|
  38. ary << value
  39. end
  40. assert_equal([1, 2, 3], ary)
  41. end
  42. def test_each_pair
  43. e = @h.each(:pair)
  44. assert_instance_of(Enumerator, e)
  45. assert_equal([:a, 1], e.next)
  46. assert_equal([:b, 2], e.next)
  47. assert_equal([:c, 3], e.next)
  48. ary = []
  49. @h.each(:pair) do |value|
  50. ary << value
  51. end
  52. assert_equal([[:a, 1], [:b, 2], [:c, 3]], ary)
  53. end
  54. def test_each_entry
  55. e = @h.each(:entry)
  56. assert_instance_of(Enumerator, e)
  57. assert_equal([:a, 1], e.next)
  58. assert_equal([:b, 2], e.next)
  59. assert_equal([:c, 3], e.next)
  60. ary = []
  61. @h.each(:entry) do |value|
  62. ary << value
  63. end
  64. assert_equal([[:a, 1], [:b, 2], [:c, 3]], ary)
  65. end
  66. def test_each
  67. e = @h.each
  68. assert_instance_of(Enumerator, e)
  69. assert_equal([:a, 1], e.next)
  70. assert_equal([:b, 2], e.next)
  71. assert_equal([:c, 3], e.next)
  72. ary = []
  73. @h.each do |value|
  74. ary << value
  75. end
  76. assert_equal([[:a, 1], [:b, 2], [:c, 3]], ary)
  77. end
  78. end
  79. end
  80.  
Success #stdin #stdout 0.03s 5840KB
stdin
Standard input is empty
stdout
Loaded suite prog
Started
.....
Finished in 0.000720 seconds.

5 tests, 25 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 25423