Ruby:Class

From Blognone

Jump to: navigation, search

Class เป็นเหมือนแบบแปลนของ Object มาลองสร้าง Class แรกกันดู

Class BankAccount
	def initialize(account_owner)
	  @owner = account_owner
	  @balance = 0
	end
 
	def deposit(amount)
	  @balance = @balance + amount
	end
 
	def withdraw(amount)
	  @balance = @balance - amount
	end
end

เราลองไล่โปรแกรมที่ละชุดนะครับ

Class BankAccount
  ...
end

เป็นการกำหนดชื่อของ Class เพื่อเรียกใช้ในภายหลัง เรานิยมสร้างชื่อของ Class ให้ตัวหน้าเป็นตัวใหญ่และคำที่ตามมาไม่มี "_" แต่ใช้ตัวอักษรใหญ่เพื่อแยกระหว่างคำ ไม่เหมือนการตั้งชื่อตัวแปร

...
	def initialize(account_owner)
	  @owner = account_owner
	  @balance = 0
	end
        ...

ใน Ruby เราสร้าง method ด้วยคำสั่ง def ตามด้วยชื่อของ method นั้นๆ ตามด้วย argument ที่ต้องการส่งให้กับ method นั้นๆ สิ่งที่พิเศษสำหรับ method นี้คือ initialize ซึ่งทำให้ method นี้เป็น method แรกที่ถูกเรียกใช้เมื่อเราแปลง Class เป็น object

@owner = account_owner

ตัวแปรที่ขึ้นต้นด้วย @ จะหมายถึง instance variable ซึ่งทำเราสามารถเรียกใช้ตัวแปรที่ชื่อ owner ได้จากที่ใดก็ได้ใน class ในบรรทัดนี้เรากำหนดให้ owner มีค่าเท่ากับ account_owner ซึ่งเป็นตัวแปรที่มีคนส่งมาให้ผ่าน argument ของ method

เมื่อเรานำ @owner และ @balance มาไว้ที่ initialize จะเป็นเหมือนเรากำหนดค่าเริ่มต้นให้กับตัวแปรทั้งสองตัวนี้ หากเราไม่เขียน initialize ภาษา Ruby จะสร้าง Object โดยมองว่า method initialize ไม่มีอะไรอยู่ข้างใน

การสร้าง Object จาก class เราสามารถทำได้ดังนี้

my_account = BankAccount.new('Russ')

เราจะได้ Object BankAccont ที่มีตัวแปร @owner เท่ากับ 'Russ' และ @balance มีค่าเริ่มต้นเท่ากับ 0

...
	def deposit(amount)
	  @balance = @balance + amount
	end
 
	def withdraw(amount)
	  @balance = @balance - amount
	end
        ...

deposit และ withdraw ใช้สำหรับการกำหนดค่าให้กับ @balance จากนั้น method จะ return ค่าสุดท้้ายให้กับคนที่เรียกมัน จะเห็นว่าสิ่งสุดท้ายที่ method นี้ทำคือกำหนดค่าให้ @balance ดังนั้นสิ่งที่ return คือ @balance

my_balance = my_account.deposit(100,000)

ค่าของ my_balance จะเท่ากับ 100,000 แต่ถ้าเราต้องการค่าของ balance โดยไม่ต้อง deposit หรือ withdraw ล่ะ