เมื่อวานนี้พูดถึงคำนิยามของ closure ไป วันนี้ผมจะนำมันมาใช้สร้างโค้ดที่มีลักษณะคล้ายโค้ดจากภาษา Object-oriented programming (OOP) ให้ดูครับ
เริ่มต้นด้วยโค้ด OOP บน Ruby ก่อน
class Prepend def initialize(start_word) @start_word = start_word end def prepend_for(end_word) @start_word + " " + end_word # Not idiomatic Ruby but should be more familiar for other languages user end end hello = Prepend.new("Hello") hello.prepend_for("Tap") # => "Hello Tap" hello.prepend_for("OOP") # => "Hello OOP"
ผมทำสร้างคลาส Prepend ซึ่งมี constructor method ที่รับพารามิเตอร์ 1 ตัวคือคำแรก (start_word) เก็บไว้เป็น instance variable และสร้างเมท็อด prepend_for ที่รับพารามิเตอร์หนึ่งตัวคือคำท้าย (end_word) นำคำแรกและคำท้ายต่อกัน