Guest User

Untitled

a guest
Jan 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. Method
  2. ------
  3.  
  4. * ใช้ keyword `def` และเมื่อจบ method ให้ปิดด้วย keyword `end`
  5. * parameter ต่อหลังชื่อ method ถ้ามีหลายตัวให้ใช้ `,` คั่นระหว่าง parameter
  6.  
  7. def say msg
  8. puts "Hello " + msg
  9. end
  10.  
  11. * method ระดับ class จะประกาศเป็น `def <ClassName>.<MethodName>` เช่น
  12.  
  13. def MyClass.classMethod
  14. puts "This is a class method"
  15. end
  16.  
  17. * Override Method ถ้าต้องการให้เรียกใช้ Method ของคลาสแม่ด้วย ใช้ `super`
  18.  
  19. class MyClass
  20. def sayHello
  21. return "Hello from MyClass"
  22. end
  23.  
  24. def sayGoodbye
  25. return "Goodbye from MyClass"
  26. end
  27. end
  28.  
  29. class MyOtherClass < MyClass
  30. # Override and Replace
  31. def sayHello
  32. return "Hello from MyOtherClass"
  33. end
  34. # Override but call Method superclass
  35. def sayGoodbye
  36. return super << " and also from MyOtherClass"
  37. end
  38. end
  39.  
  40. * เราสามารถใช้ method `send` เพื่อเข้าไปเรียกใช้ method ที่มี accessmodifiers แบบ `private` หรือ `protected` ได้
  41.  
  42. ob.send(:methodname)
  43.  
  44. * singleton method ทำได้ด้วยประกาศ `def objectname.methodname (argument)`
  45. * singleton class ประกาศ `class << objectname`
  46. * nested method ใช้เพื่อประกาศ method ใน method อีกทีซึ่งต้องเรียก method ที่หุ้ม nested method ก่อน ดังตัวอย่าง
  47.  
  48. class X
  49. def x
  50. puts "x:"
  51.  
  52. def y
  53. puts "y:"
  54. end
  55.  
  56. def z
  57. puts "z:"
  58. y
  59. end
  60. end
  61. end
  62.  
  63. ob = X.new
  64. ob.x
  65. ob.y
  66. ob.z
  67.  
  68. * ถ้าชื่อ method ขึ้นด้วยตัวใหญ่ __Ruby__ ต้องใส่ `()` ติดหลังไปด้วย ไม่เช่นนั้นจะถือว่านั้นคือ `constant` เช่น
  69.  
  70. def Fred
  71. puts "say"
  72. end
  73.  
  74. Fred # uninitialized constant Fred (NameError)
  75. Fred() # output say
Add Comment
Please, Sign In to add comment