Ruby:Symbols

From Blognone

Jump to: navigation, search

Symbol ถือเป็น object พิเศษแบบหนึ่ง นั่นคือ มันจะมีแค่ตัวเดียวเสมอ (ถ้าชื่อเหมือนกัน) เวลาประกาศจะขึ้นต้นด้วย colon

a = :a_symbol
b = :an_other_symbol
c = :first_name

ความแตกต่างระหว่าง String และ Symbol อยู่ที่การจัดการข้อมูลในหน่วยความจำ

สมมติเราใช้ Symbol :a ไป 10 ครั้งใน program จะมี object symbol :a เกิดขึ้นใน memory แค่ตัวเดียว แต่ถ้าเราใช้ String 'a' 10 ครั้งใน program จะมี object string 'a' เกิดขึ้น 10 ตัวใน memory

Symbol ตัวแปลที่มีค่าเท่ากันจะใช้ id เดียวกัน

a = :apple
=> :apple
a.id
=> 201138
b = :apple
=> :apple
b.id
=> 201138

String ถึงตัวแปลจะมีค่าเท่ากัน แต่ไม่ได้ใช้ id เดียวกัน

a = "apple"
=> "apple"
a.id
=> 1734860
b = "apple"
=> "apple"
b.id
=> 1730800


ชาว Ruby มักใช้มันตอนที่ต้องการแสดงความเป็นตัวชี้ (identifiers) เพราะเวลาเขียนต่างจาก String และตัวชี้มักเป็นค่าที่ไม่เปลี่ยนแปลง

Food.eat :all, :by => "hand", :on => "table"

หรือใช้ในคำสั่ง find ของ rails

Employee.find :all, :conditions => {:name => "Paul"}