Ruby :: Substituting variables into string

Posted by PunNeng, Wed Jan 03 04:25:00 UTC 2007

กลับมาที่ Ruby กันต่อ ยังคงวนเวียนกับเรื่อง String อีกนานครับ

คราวนี้ จะเล่าถึงการสร้าง string ซึ่งเราจะเอาตัวแปรที่สร้างขึ้นมาหรือ expression ไปแสดงใน string นั้นๆ ด้วย

การจะเอาตัวแปรเข้าไปแสดงใน string สามารถทำได้โดย

number = 5
"The number is #{number}."      # => "The number is 5."
"The number is #{5}."           # => "The number is 5."
"The number after #{number} is #{number.next}."
# => "The number after 5 is 6."
"The number prior to #{number} is #{number-1}."
# => "The number prior to 5 is 4"
"We're ##{number}"              # => "We're #5!"

เราสามารถใช้ #{} ในการแสดงตัวแปรใน string ซึ่งไอ้เครื่องหมายแปลกๆ นี้เนี่ย ถ้าไม่ใช่ expression มันจะไปเรียก to_s method แล้วก็แทนที่ลงไป หรือถ้าไม่ใช้ เครื่องหมายนี้ สามารถใช้แบบนี้ได้ ​

"The number is " << number.to_s   # => "The number is 5"

นอกจากนี้ เรายังสามารถใส่ code เข้าไปใน #{} ได้อีกด้วย ซึ่งบางทีมันก็อาจจะได้ใช้งานบ้าง (ตั้งแต่อยู่กับมันมา ยังไม่เคยได้ใช้เลยครับ)

%{Here is #{class InstantClass
    def bar
        "some text"
    end
end
InstantClass.new.bar
}.}
# => "Here is some text."

class ที่เพิ่งสร้างแล้วเรียกใช้งานมานี้ ยังสามารถเรียกใช้จากข้างนอก\ #{} นี้ได้อีกด้วย แต่บางทีก็มีผลข้างเคียงหน่อย เวลาที่ใช้ตัวแปรข้างใน #{} อาจจะไปชนซ้ำกับตัวแปรตัวอื่น ไม่ค่อยดีเท่าไหร่ แต่ก็น่าจะรู้เอาไว้

"I've have set x to #{x = 5; x += 1}."   # => "I've set x to 6."
x                                        # => 6

สามารถหลีกเลี่ยงผลกระทบนี้โดยใส่ \ ไปข้างหน้า #{} หรือว่าใช้เอาไว้ใน single quote แทน

"\#{foo}"                # => "\#{foo}"
'#{foo}'                 # => "\#{foo}"

ตัว #{} ก็จะไม่ทำงาน

เรายังสามารถใช้รูปแบบ "here document" เป็นอีกทางเลือกหนึ่งของการใช้ %{} ซึ่งสองโครงสร้างนี้ จะทำให้ string เรา อ่านง่ายขึ้น โดยที่เราสามารถประกาศ string หลายๆ บรรทัดได้ เช่น

name = "Mr. Neng"
email = <<END
Dear #{name}

Unfortunately, we cannot ... bla bla
bla bla
END

หรือเราสามารถใช้รูปแบบ "here document" โดยที่ไม่ต้องเอาไปใส่ตัวแปร ก็ได้

<<end_of_poem
There once ... bla bla
bla bla...
end_of_poem
# => "There once ... bla bla\nbla bla..."

แก้ไขล่าสุด วันที่ 23 กรกฏาคม 2550 เวลา 1.36 น.

Filed Under: Ruby | Tags: howto ruby string

Comments

Have your say

A name is required. You may use HTML in your comments.




codegent: we're hiring