Object inheritance ของ ruby

ไหนๆ เขียนเรื่อง Object แล้วถ้าไม่เขียนเรื่อง Inheritance, include module ก็จะไม่ครบวงจร

การสืบทอดความสามารถของ class แม่ในภาษา ruby ใช้เครื่องหมาย "<" เป็นสัญลักษณ์ประมาณว่า เอาความสามารถของด้านขวาไปใส่ด้านซ้าย

  1. class Circle
  2.   attr_accessor :circle, :radious
  3.   class << self; attr_accessor :count end
  4. end
  5.  
  6. class Ring < Circle
  7. end
  8.  
  9. ring = Ring.new
  10. ring.circle = 5
  11. puts ring.circle #=> 5
  12.  
  13. Ring.count = 3
  14. Circle.count = 8
  15. puts Ring.count #=> 3
  16. puts Circle.count #=> 8

จากตัวอย่าง Ring ได้คุณสมบัติทุกอย่างจาก Circle ทั้ง class level และ instance level แต่ไม่ได้

ใช้ค่าของ count ร่วมกัน หากต้องการให้ใช้ร่วมกันเราต้องเขียนความสัมพันธ์ขึ้นมาเอง เช่น

  1. class Ring < Circle
  2.   def count=(c)
  3.     Circle.count = c  
  4.   end
  5. end

ใน ruby ยังมีการดึงคุณสมบัติอีกแบบโดยการ include module

  1. module Sing
  2.   def wing
  3.     "Say wing!!"
  4.   end
  5. end
  6.  
  7. class Circle
  8.   include Sing
  9. end
  10.  
  11. circle = Circle.new
  12. circle.wing

การ include module ก็คล้ายกับการเอา code ใน module มาใส่ไว้ใ inherite น class ช่วยลดการเขียนที่ทำซ้ำๆ กันในแต่ละ Object ได้มากทีเดียว อย่าลืมว่า Object ของ ruby จะ inherit ได้แค่ Object เดียว ถ้าต้องการมากกว่านั้นก็มา include เอา (ส่วน concept ของการเลือก include หรือ inherit ไว้ค่อยเขียนกันอีกที)

เมื่อเราเรียก method wing ใน class Circle สิ่งที่ ruby ทำคือไปหา method wing ใน Circle ก่อน หากไม่เจอ จึงไปหาใน module โดยไล่จากตัวสุดท้ายไปหาตัวแรก เมื่อไม่เจอใน module จึงขึ้นไปหาที่ Super class ของ circle ต่อไป แล้วตามไปหาใน module ของ circle เป็นลำดับ ไปจนสิ่นสุดที่ Object

ที่มา -- railstips.org

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.