Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Method
- ------
- * ใช้ keyword `def` และเมื่อจบ method ให้ปิดด้วย keyword `end`
- * parameter ต่อหลังชื่อ method ถ้ามีหลายตัวให้ใช้ `,` คั่นระหว่าง parameter
- def say msg
- puts "Hello " + msg
- end
- * method ระดับ class จะประกาศเป็น `def <ClassName>.<MethodName>` เช่น
- def MyClass.classMethod
- puts "This is a class method"
- end
- * Override Method ถ้าต้องการให้เรียกใช้ Method ของคลาสแม่ด้วย ใช้ `super`
- class MyClass
- def sayHello
- return "Hello from MyClass"
- end
- def sayGoodbye
- return "Goodbye from MyClass"
- end
- end
- class MyOtherClass < MyClass
- # Override and Replace
- def sayHello
- return "Hello from MyOtherClass"
- end
- # Override but call Method superclass
- def sayGoodbye
- return super << " and also from MyOtherClass"
- end
- end
- * เราสามารถใช้ method `send` เพื่อเข้าไปเรียกใช้ method ที่มี accessmodifiers แบบ `private` หรือ `protected` ได้
- ob.send(:methodname)
- * singleton method ทำได้ด้วยประกาศ `def objectname.methodname (argument)`
- * singleton class ประกาศ `class << objectname`
- * nested method ใช้เพื่อประกาศ method ใน method อีกทีซึ่งต้องเรียก method ที่หุ้ม nested method ก่อน ดังตัวอย่าง
- class X
- def x
- puts "x:"
- def y
- puts "y:"
- end
- def z
- puts "z:"
- y
- end
- end
- end
- ob = X.new
- ob.x
- ob.y
- ob.z
- * ถ้าชื่อ method ขึ้นด้วยตัวใหญ่ __Ruby__ ต้องใส่ `()` ติดหลังไปด้วย ไม่เช่นนั้นจะถือว่านั้นคือ `constant` เช่น
- def Fred
- puts "say"
- end
- Fred # uninitialized constant Fred (NameError)
- Fred() # output say
Add Comment
Please, Sign In to add comment