Tik’s Blog

ร้อยแปดพันเก้า

Posts Tagged ‘ruby

block_given? ใน Ruby

without comments

ได้ลองเปิดซอร์สโค้ด Rack ดูเล่นๆ เห็นมีใช้ OptionParser อยู่…ด้วยความที่เป็นมือใหม่อยากรู้ว่ามันทำงานยังไงเลยลอง google ดู API ซึ่งมี initializer ที่รับ argument แค่ 3 ตัวเท่านั้น แต่ไม่เห็นมีรับ block เลย  หลังอ่านโค้ดดูเลยเห็นว่าทริกมันอยู่ที่บรรทัดสุดท้าย:


# File optparse.rb, line 777
def initialize(banner = nil, width = 32, indent = ' ' * 4)
...
yield self if block_given?
end

block_given? เป็น method ของ Kernel ที่เอาไว้เช็คว่า yield มี block อะไรต้อง execute หรือเปล่า  เจ๋งจริง

Written by sukita

กุมภาพันธ์ 5, 2009 at 11:05 pm

บันทึกโพสใน Programming

Tagged with