原文

1. block中的 yield 与遍历

5.times do |i|
    puts i
end

或者

def my_times(n)
    i = 0
    while n > i
      i += 1
      yield i
    end
  end

  my_times(5) { |num|
    puts "hello, #{num}xRuby"
  }

  # 得到結果
  # hello, 1xRuby
  # hello, 2xRuby
  # hello, 3xRuby
  # hello, 4xRuby
  # hello, 5xRuby

  

2. block 物件化

由于 block不能单独存在。可以借助 Proc.new

比如

greeting = Proc.new { puts "哈囉,世界" }   # 使用 Proc 類別可把 Block 物件化

或者

say_hello_to = Proc.new { |name| puts "你好,#{name}"}
say_hello_to.call("尼特羅會長")

调用

say_hello_to.call("尼特羅會長")    # 使用 call 方法
say_hello_to.("尼特羅會長")        # 使用小括號(注意,有多一個小數點)
say_hello_to["尼特羅會長"]         # 使用中括號
say_hello_to === "尼特羅會長"      # 使用三個等號
say_hello_to.yield "尼特羅會長"    # 使用 yield 方法

 

结束

相关文章:

  • 2021-12-13
  • 2022-12-23
  • 2021-11-18
  • 2021-06-22
  • 2021-07-02
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2021-08-02
相关资源
相似解决方案