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

Ruby String Formatting ง่ายๆ: Leading Zeros, Columns และ printf Style

มาพูดถึงการ format strings ใน Ruby กัน

ทำไมต้อง format string? อาจอยาก leading zero แม้เลขต่ำกว่า 10 (เช่น 01, 02, 03...), หรือ console output เรียง columns ให้สวย

ภาษาอื่นใช้ printf format strings ถ้าคุณเคยเขียน C คงคุ้นเคย ใน printf ต้องกำหนด format specifiers และ variables/values

เริ่มต้น Ruby String Formatting

แม้ sprintf จะมีใน Ruby แต่เราจะใช้วิธีที่ idiomatic กว่า (style guide ไม่เห็นต้องการกัน แต่ผมคิดว่าโอเค)

ตัวอย่าง:

 time = 5 message = "Processing of the data has finished in %d seconds" % [time] puts message 

Output => "Processing of the data has finished in 5 seconds"

ในตัวอย่าง %d คือ format specifier (รายการ specifiers ที่นี่) และ time คือ variable ที่ต้องการ format %d ให้ whole numbers

อยากแสดง floating point ใช้ %f ระบุ decimal places ได้: %0.2f

2 หมายถึงเก็บแค่ 2 ตำแหน่งทศนิยม

ตัวอย่าง:

 score = 78.5431 puts "The average is %0.2f" % [score]

Output => The average is 78.54

จำว่าเลขจะปัดเศษ เช่น 78.549 จะพิมพ์ 78.55

การแปลงและ Padding

แปลง decimal เป็น hexadecimal ด้วย %x:

 puts "122 in HEX is %x" % [122] 

Output => 122 in HEX is 7a

Padding string:

Format padding เลขด้วย 0 ตามต้องการ: %0<จำนวนศูนย์>d

puts "The number is %04d" % [20]

Output => The number is 0020

ใช้ ruby string format สร้าง aligned columns เปลี่ยน 0 เป็น dash:

Ruby String Formatting ง่ายๆ: Leading Zeros, Columns และ printf Style

ทางเลือก: ใช้ .ljust และ .rjust จาก String class

ตัวอย่าง:

 names_with_ages = [["john", 20], ["peter", 30], ["david", 40], ["angel", 24]] names_with_ages.each { |name, age| puts name.ljust(10) + age.to_s } # พิมพ์ตารางดังนี้ john 20 david 30 peter 40 angel 24 

สรุป

เห็นแล้ว ruby & rails string formatting ง่ายมาก ต้องเข้าใจ format specifiers ที่มี

หวังว่าคุณเพลิดเพลินกับการเดินทางสู่โลก output formatting! อย่าลืมสมัครรับ newsletter 🙂