在ruby-koans中接触到yield和block的使用,刚接触有点疑惑,也有兴趣往下挖掘看看yield block的神奇所在。
1. yield占位。首先截取ruby-koans中关于yield和block的用法的实例。
def method_with_block result = yield result end def test_methods_can_take_blocks yielded_result = method_with_block { 1 + 2 } assert_equal 3, yielded_result end def test_blocks_can_be_defined_with_do_end_too yielded_result = method_with_block do 1 + 2 end assert_equal 3, yielded_result end
def method_with_block result = { 1 + 2 } result end yielded_result = method_with_block终于method_with_block执行代码块后将结果3返回出来最后被赋值给yielded_result. 于是yield的使命完成了。
# ------------------------------------------------------------------ def method_with_block_arguments yield("Jim") end def test_blocks_can_take_arguments method_with_block_arguments do |argument| assert_equal "Jim", argument end end # ------------------------------------------------------------------ def many_yields yield(:peanut) yield(:butter) yield(:and) yield(:jelly) end def test_methods_can_call_yield_many_times result = [] many_yields { |item| result << item } assert_equal [:peanut, :butter, :and, :jelly], result end
def method_with_explicit_block(&block) block.call(10) end def test_methods_can_take_an_explicit_block_argument assert_equal 20, method_with_explicit_block { |n| n * 2 } add_one = lambda { |n| n + 1 } assert_equal 11, method_with_explicit_block(&add_one) end