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

3 วิธีอันทรงพลัง ใช้ประโยชน์จาก Ruby's Gsub Method

มาพูดถึง gsub ใน Ruby และวิธีใช้ — ต้องมี String ก่อน เพราะจุดประสงค์ gsub คือ Replace ส่วนของ String

จริงๆ แล้ว: "sub" ใน "gsub" = "Substitute" (แทนที่), "g" = "Global" (ทั่วทั้งสตริง)

String ตัวอย่าง:

str = "white chocolate" 

อยาก Replace "white" ด้วย "dark" — ทำแบบนี้:

str.gsub("white", "dark")

มันหมายถึง: ใน str แทนที่ ทุกครั้ง ของคำแรก (white) ด้วยคำที่สอง (dark) — ได้กิน Chocolate ดีขึ้น (แตแค่ String กินไม่ได้ 🙂)

어쨌든... gsub ทำได้มากกว่า Simple Substitution — มาดูตัวอย่าง

แทนที่ Patterns ด้วย Regular Expression

Replace คำเดี่ยวโอเค — แต่อยาก Replace Pattern ได้ไหม?

เช่น: ปี, อีเมล, เบอร์โทร ฯลฯ — ทำได้!

ตัวอย่าง:

"a1".gsub(/\d/, "2") # "a2" 

Argument แรก = Regular Expression — Pattern Matching Language — \d หาตัวเลข (เช่น "1" ใน "a1")

ยังทำได้:

"a1".gsub(/(\w)(\d)/, '\2\1')

ผลลัพธ์: "1a" — สลับลำดับ!

用 "Capture Groups" — ใช้ Groups เป็น \1 Group แรก, \2 Group ที่สอง ฯลฯ — Groups สร้างด้วยวงเล็บ

Advanced Gsub กับ Blocks

น่าสนใจตอน用 gsub กับ Block — เพราะใน Block ใช้ Logic ตัดสินใจ Replace ยังไง แทน Static Value

ตัวอย่าง:

"dog".gsub(/\w+/) { |animal| animal == "dog" ? "cat" : "dog" }

หาสัตว์ด้วย \w+ (1+ Alphanumeric) — แล้ว: เป็น "dog" -> Replace "cat", อื่นๆ -> Replace "dog"

Logic แบบนี้ Static Value (Argument ที่ 2 ของ gsub) ทำไม่ได้

แทนที่ Multiple Terms ด้วย Hash

มี List ของ Substitutions — 用 Hash ได้

แบบนี้:

colors = { "B" => "blue", "G" => "green", "R" => "red" }

ทำงานแบบ Dictionary แปล — Keys จะถูก Replace ด้วย Values

ตัวอย่าง:

"BBBGR".gsub(/\w/, colors)

ผลลัพธ์: "bluebluebluegreenred" — ให้ Arg 1 Match Keys (ที่นี่ \w Match ตัวอักษรเดี่ยว B->blue)

Summary (สรุป)

คุณเรียนรู้ gsub ใน Ruby! เมธอดทรงพลัง Replace/Substitute ตัวอักษรใน String

หลาย Use Cases:

  • ลบ Invalid Characters (Arg 2 = Empty String)
  • แทนที่ Placeholders & Acronyms ด้วยค่าเต็ม
  • 用 Patterns & Logic เปลี่ยน String

3 วิธีอันทรงพลัง ใช้ประโยชน์จาก Ruby s Gsub Method

ตอนนี้ Practice ให้จดจำ — ขอบคุณที่อ่าน 🙂