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

เชี่ยวชาญ Ruby String Concatenation & Interpolation: ตัวอย่างปฏิบัติ

รวมสตริงหลายตัวเข้าด้วยกัน — ทำบ่อยใน Ruby — ทำยังไง?

มี 2 วิธี:

  1. Ruby String Concatenation (ต่อสตริง)
  2. Ruby String Interpolation (แทรกค่าตัวแปรในสตริง)

Concatenation long แบบนี้:

 a = "Nice to meet you"
b = ", "
c = "do you like blueberries?"
a + b + c # "Nice to meet you, do you like blueberries?" 

用 + Operator ต่อสตริง — a + b + c สร้าง New String

ไม่ต้อง Variables — ตัวอย่าง:

 puts "I like" + " " + "chocolate" # I like chocolate 

อีกทางคือ += Operator:

 a = ""
a += "test"
a += "test"
a += "test"
a # "testtesttest" 

เริ่ม Empty String แล้ว Append สร้างใหญ่ขึ้น — แต่มีปัญหา: มันช้ามาก!

โซลูชันต่อไป...

Ruby Concat Method Example

用 concat Method รวมสตริงได้มีประสิทธิภาพ

ทำแบบนี้:

 str = ""
str.concat("a")
str.concat("a")
str # "aa" 

เร็วกว่าเพราะเปลี่ยน str ตรงๆ แทนสร้างใหม่ — แต่ concat ไม่สวยเท่า +=...

มีทางอื่นไหม? มี! 用 << Method — Alias ของ concat

Note: ตั้งแต่ Ruby 2.4 concat ส่ง Multiple Arguments ได้ << ส่งทีละ 1 ตัว

ตัวอย่าง:

 str = ""
str << "a"
str << "a" 

ยังทำได้:

 str = ""
str << "a" << "a" 

แต่ยังมีปัญหา — รวม String กับ Variables แต Variable ไหนไม่ใช่ String = ผลไม่คาดคิด

ดูสิ:

 "" + 1 # TypeError: no implicit conversion of Fixnum into String
"" << 1 # "\x01" 

โซลูชัน? 用 to_s แปลง Objects เป็น Strings

แบบนี้:

 "" + 1.to_s 

แต่มัน醜 (Ugly) เร็ว — มี Tool อีกตัว

วิธีใช้ Ruby String Interpolation

Interpolation = Merge Variables เข้า String — เทคนิคทรงพลัง

ทำให้ "Templatize" String ได้

ตัวอย่าง:

 age = 33
name = "Jesus"
"Hello, my name is #{name} & I'm #{age} years old." 

เสียบ name age ใส่ได้โดยตั้ง Variables ก่อน String

จุดดีที่สุด? Ruby แปลงค่าเป็น String ให้อัตโนมัติ — ไม่ต้อง to_s!

Good stuff.

Prepending Strings (เพิ่มข้างหน้า)

อีกวิธีรวม Strings — แทน Interpolation หรือ Append ท้ายด้วย <</concat

用 prepend ได้!

ตัวอย่าง:

 str = ""
str.prepend("1")
str.prepend("2")
str.prepend("3")
# "321" 

คิดว่ามี append Method — ไม่มี (Arrays เท่านั้น)

Summary (สรุป)

คุณเรียนรู้ String Concatenation, Appending, Prepending, Interpolation ใน Ruby — รวม Multiple Strings ได้

Share บทความถ้าUseful 🙂 — ขอบคุณที่อ่านครับ