Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

Ruby Methods เห็นใจง่าย: สร้าง Custom Functions ได้ง่ายๆ

Ruby Method คืออะไร? — 1 หรือหลายบรรทัด Ruby Code จัดกลุ่มเพื่อ Purpose เฉพาะ

Grouped Code ได้ชื่อ ใช้ซ้ำได้ทุกครั้ง ไม่ต้องเขียนหรือ Copy-Paste ซ้ำ

Purpose ของ Method:

  • GET Information
  • CHANGE หรือ CREATE Objects
  • FILTER & FORMAT Data

Example 1: size บน Array ให้จำนวน Elements (Get Info)

Example 2: pop ลบ Element สุดท้ายจาก Array (Change Objects)

เข้าใจความสัมพันธ์ Objects, Classes, Methods ทุกอย่างจะเข้าใจง่ายขึ้น

Ruby Methods เห็นใจง่าย: สร้าง Custom Functions ได้ง่ายๆ

เรียนต่อ!

วิธี Define Methods

Ruby มี Built-in Methods เยอะ — แตสร้าง เองได้

ยังไง? 用 def Keyword Define Instance Method

Syntax:

def gimme_bacon
  puts "Bacon plz."
end

เกิดอะไรขึ้น?

  1. def = Syntax บอก Ruby อยาก Define Method
  2. gimme_bacon = ชื่อ Method
  3. puts "Bacon plz." = Body ของ Method
  4. end = จบ Definition

Define Method = บอก Ruby อยากสร้าง — อยากใช้ต้อง Call Method

วิธี Call Methods ใน Ruby

ใน Ruby ใช้ Method = เรียกว่า "Calling It" — ได้ยิน "Method Call" หรือ "Sending a Message" (OOP Purist)

ไม่ว่าจะไหน... มาดู Example

นี่:

gimme_bacon

Prints: "Bacon plz."

Call Methods บน Objects ได้ — เช่น:

n = [1,2,3]
n.size # 3

n.size เรียก Method size บน Object n (Array) — ได้ Size

Methods ใดพร้อมใช้?

ขึ้นอยู่กับ Class ของ Object — Array มี Methods ต่าง Hash

เช็ค Ruby Documentation หา List Methods ของ Class นั้น

Returning Values จาก Methods

Key Concept: ALL Methods Return a Value

ผลลัพธ์จากการ Call Method = ค่าจาก Expression สุดท้ายใน Definition

เช่นนี้:

def number_one
  1
end
number_one # 1

อีกตัว:

def add(x,y)
  x + y
end
add(5, 6) # 11

เรียกว่า "Implicit Return" — ชื่อหรูสำหรับ "Auto Return Last Thing"

เพิ่มเติม: บอก Ruby return ด้วย Keyword ได้

def two
  return 2
end
# 2

สังเกต Method หยุดทำงานตอน用 return — 用 Early Return หรือ Exit Loop

ทำไม Method Name มี Question Mark?

อาจเจอ Methods แปลก — ชื่อแบบ: empty?, sort!, title= — ทั้งหมด Valid Method Names

Question Mark, Exclamation Mark, Equals Sign หมายถึงอะไร? — Convention ของ Ruby Community

อธิบาย:

  • Question Mark Method (Predicate Method) = ควรคืน true หรือ false
  • Exclamation Mark Method (Bang Method) = ทำอย่างอื่นจาก Version ไม่มี ! — มักเปลี่ยน Object เอง (Add/Delete Elements)
  • Equals Sign Method = Assignment — ใส่ค่า Instance Variable

Conventions ไม่ Enforced โดยภาษา — แต่... Follow แล้วเขียน Ruby-like Code ได้!

Summary (สรุป)

คุณเรียนรู้ Ruby Methods — Define, Use, Conventions

ตอนนี้ถึงคุณ Practice 🙂 — ขอบคุณที่อ่านครับ!