1 require File.expand_path(File.dirname(__FILE__) + '/edgecase')
3 class AboutBlocks < EdgeCase::Koan
9 def test_methods_can_take_blocks
10 yielded_result = method_with_block { 1 + 2 }
11 assert_equal __, yielded_result
14 def test_blocks_can_be_defined_with_do_end_too
15 yielded_result = method_with_block do 1 + 2 end
16 assert_equal __, yielded_result
19 # ------------------------------------------------------------------
21 def method_with_block_arguments
25 def test_blocks_can_take_arguments
26 result = method_with_block_arguments do |argument|
27 assert_equal __, argument
31 # ------------------------------------------------------------------
40 def test_methods_can_call_yield_many_times
42 many_yields { |item| result << item }
43 assert_equal __, result
46 # ------------------------------------------------------------------
56 def test_methods_can_see_if_they_have_been_called_with_a_block
57 assert_equal __, yield_tester { :with_block }
58 assert_equal __, yield_tester
61 # ------------------------------------------------------------------
63 def test_block_can_affect_variables_in_the_code_where_they_are_created
64 value = :initial_value
65 method_with_block { value = :modified_in_a_block }
66 assert_equal __, value
69 def test_blocks_can_be_assigned_to_variables_and_called_explicitly
70 add_one = lambda { |n| n + 1 }
71 assert_equal __, add_one.call(10)
73 # Alternative calling sequence
74 assert_equal __, add_one[10]
77 def test_stand_alone_blocks_can_be_passed_to_methods_expecting_blocks
78 make_upper = lambda { |n| n.upcase }
79 result = method_with_block_arguments(&make_upper)
80 assert_equal __, result
83 # ------------------------------------------------------------------
85 def method_with_explicit_block(&block)
89 def test_methods_can_take_an_explicit_block_argument
90 assert_equal __, method_with_explicit_block { |n| n * 2 }
92 add_one = lambda { |n| n + 1 }
93 assert_equal __, method_with_explicit_block(&add_one)