パーフェクトRuby読書会

3-5-8 ブロック途中から(P.98-)

In [2]:
def with_current_time
  yield Time.now
end

with_current_time do |now|
  puts now.to_s
end
2014-12-17 20:06:21 +0900
In [3]:
with_current_time do
  puts 'Hi'
end
Hi
In [4]:
with_current_time do |now, hogehoge|
  puts hogehoge.inspect
end
nil
In [5]:
def default_argument_for_block
  yield
end

default_argument_for_block do |val = 'Hi'|
  puts val
end
Hi
In [6]:
def flexible_arguments_for_block
  yield 1, 2, 3
end

flexible_arguments_for_block do |*params|
  puts params.inspect
end
[1, 2, 3]
In [14]:
def block_sample(&block)
  puts 'stand up'
  block.call if block
  puts 'sit down'
end

block_sample do 
  puts 'hoge'
  puts 'fuga'
end
stand up
hoge
fuga
sit down
In [15]:
block_sample
stand up
sit down

次回はP.100 Procから

In [ ]: