&tag(Ruby/ブロック);
# 1. 普通のブロック
3.times do
puts "hello1"
end
puts ""
# 2. ブロックの中でProcを呼び出す
proc = Proc.new {puts "hello2"}
3.times do
proc.call
end
puts ""
# 3. Procに&をつけて渡すとブロックとして扱われる
3.times(&proc)
# 4. メソッドの仮引数に&をつけるとブロックをProcオブジェクトとして扱える
def sample(&block)
block.call('abc', 'def')
end
sample do |a, b|
puts "#{a} #{b}"
end
class Person attr_accessor :name end p1 = Person.new p1.name = '田中' p2 = Person.new p2.name = '佐藤' p3 = Person.new p3.name = '鈴木' persons = [p1, p2, p3] p persons.map(&:name) # ["田中", "佐藤", "鈴木"] p persons.map(&:object_id) #[70144881868780, 70144881868740, 70144881868700]