当前位置: 代码迷 >> 综合 >> [ruby koan] about_block
  详细解决方案

[ruby koan] about_block

热度:25   发布时间:2024-02-19 13:10:11.0

[ruby koan] about_block

block 的2种形式

  • {...}

  • do ... end

  def test_methods_can_take_blocksyielded_result = method_with_block { 1 + 2 }assert_equal 3, yielded_resultend
?def test_blocks_can_be_defined_with_do_end_tooyielded_result = method_with_block do 1 + 2 endassert_equal 3, yielded_resultend

block可以获取参数

  • 通过 yield() 给 block 传参

  • yield() 可以多次调用,传递多个参数

  • 使用 || 声明参数列表,比如 { |item| access item }

  def method_with_block_argumentsyield("Jim")end
?def test_blocks_can_take_argumentsmethod_with_block_arguments do |argument|assert_equal "Jim", argumentendenddef many_yieldsyield(:peanut)yield(:butter)yield(:and)yield(:jelly)end
?def test_methods_can_call_yield_many_timesresult = []many_yields { |item| result << item }assert_equal [:peanut, :butter, :and, :jelly], resultend

方法可以感知是否有使用block来调用

  def yield_testerif block_given?yieldelse:no_blockendend
?def test_methods_can_see_if_they_have_been_called_with_a_blockassert_equal :with_block, yield_tester { :with_block }assert_equal :no_block, yield_testerend

block的一些性质

  • 可以修改block外的变量

  • 可以被赋值成变量并显示调用

  • 可以作为参数,传递给期待block的函数

  def test_block_can_affect_variables_in_the_code_where_they_are_createdvalue = :initial_valuemethod_with_block { value = :modified_in_a_block }assert_equal :modified_in_a_block, valueend
?def test_blocks_can_be_assigned_to_variables_and_called_explicitlyadd_one = lambda { |n| n + 1 }assert_equal 11, add_one.call(10)
?# Alternative calling syntaxassert_equal 11, add_one[10]end
?def test_stand_alone_blocks_can_be_passed_to_methods_expecting_blocksmake_upper = lambda { |n| n.upcase }result = method_with_block_arguments(&make_upper)assert_equal "JIM", resultend
?# ------------------------------------------------------------------
?def method_with_explicit_block(&block)block.call(10)end
?def test_methods_can_take_an_explicit_block_argumentassert_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
?
end