1 require File.expand_path(File.dirname(__FILE__) + '/edgecase')
3 class AboutIteration < EdgeCase::Koan
5 def test_each_is_a_method_on_arrays
6 [].methods.include?("each")
9 def test_iterating_with_each
18 def test_each_can_use_curly_brace_blocks_too
27 def test_break_works_with_each_style_iterations
28 array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
37 def test_collect_transforms_elements_of_an_array
39 new_array = array.collect { |item| item + 10 }
40 assert_equal __, new_array
42 # NOTE: 'map' is another name for the 'collect' operation
43 another_array = array.map { |item| item + 10 }
44 assert_equal __, another_array
47 def test_select_selects_certain_items_from_an_array
48 array = [1, 2, 3, 4, 5, 6]
50 even_numbers = array.select { |item| (item % 2) == 0 }
51 assert_equal __, even_numbers
53 # NOTE: 'find_all' is another name for the 'select' operation
54 more_even_numbers = array.find_all { |item| (item % 2) == 0 }
55 assert_equal __, more_even_numbers
58 def test_find_locates_the_first_element_matching_a_criteria
59 array = ["Jim", "Bill", "Clarence", "Doug", "Eli"]
61 assert_equal __, array.find { |item| item.size > 4 }
64 def test_inject_will_blow_your_mind
65 result = [2, 3, 4].inject(0) { |sum, item| sum + item }
66 assert_equal __, result
68 result2 = [2, 3, 4].inject(1) { |product, item| product * item }
69 assert_equal __, result2
72 # Describe in your own words what inject does.
75 def test_all_iteration_methods_work_on_any_collection_not_just_arrays
76 # Ranges act like a collection
77 result = (1..3).map { |item| item + 10 }
78 assert_equal __, result
80 # Files act like a collection of lines
81 File.open("example_file.txt") do |file|
82 upcase_lines = file.map { |line| line.strip.upcase }
83 assert_equal __, upcase_lines
86 # NOTE: You can create your own collections that work with each,
90 # Bonus Question: In the previous koan, we saw the construct:
92 # File.open(filename) do |file|
93 # # code to read 'file'
96 # Why did we do it that way instead of the following?
98 # file = File.open(filename)
99 # # code to read 'file'
101 # When you get to the "AboutSandwichCode" koan, recheck your answer.