サンプル1
test.rb
def test1
p "test1"
end
test1
test1 do
p "test1-block"
end
#######
def test2
p "test2"
yield
yield # 複数回も可能
end
# test2 と実行するとエラー `test2': no block given (yield) (LocalJumpError)
test2 do
p "test2-block"
end
###### 引数をブロックに渡す
def test3
p "test3"
yield "こんにちは"
end
test3 do |text|
p "1"
p text
p "2"
end
実行結果
"test1"
"test1"
"test2"
"test2-block"
"test2-block"
"test3"
"1"
"こんにちは"
"2"
サンプル2(実行順序)
test2.rb
class Test
def initialize
p "1"
yield self if block_given?
p "7"
end
def self.test
self.new() do |core|
p "2"
yield core if block_given?
p "5"
core.run
p "6"
end
end
def run
p "run"
end
end
#test = Test.new
Test.test do |test|
p "3"
p test
p "4"
end
実行結果
"1"
"2"
"3"
#<Test:xxxxxxx>
"4"
"5"
"run"
"6"
"7"