I'm a Ruby on Rails / jQuery web developer. Follow me at @sikachu

Squish it!

May 17th, 2009 Posted in Programming, Ruby, Ruby on Rails

ต้องบอกว่า Ruby on Rails นั้นมี helper methods เยอะจริงๆ และบางครั้งถ้าเราไม่ได้เข้าไปดูใน api documentation เราก็จะไม่พบว่ามันมีเมธอดเอาไว้ทำอะไรบ้าง

วันนี้ผมเจอ method นึงครับ ซึ่งคิดว่าน่าจะมีประโยชน์ และน่าจะมีใครต้องใช้เมธอดนี้แน่ๆ

มีใครบ้างไหมครับ ที่เคยเห็น user ชอบโพสข้อมูลมาเว้นบรรทัดๆๆๆ หลายๆ อัน หรือว่าชอบเคาะ space bar เว้นห่างๆ กัน ทำให้บางครั้งมันดูไม่เรียบร้อย และมันอ่านยาก .. วันนี้ผมมี method มาแนะนำครับ ชื่อว่า #squish

ตัวอย่างในการใช้งานก็เป็นอย่างนี้ครับ

>> str = %(hello
world)
=> "hello\nworld"
>> str.squish
=> "hello world"
>> str = "the      quick    brown     fox  jumped  over lazy    dog"
=> "the      quick    brown     fox  jumped  over lazy    dog"
>> str.squish
=> "the quick brown fox jumped over lazy dog"
>>

จะเห็นได้ว่ามันเอา space และ new line (\n) ออกด้วย .. แต่ผมคิดว่ามันจะเวิร์คกว่านี้ ถ้ามันยังคง \n เอาไว้ ทำแค่บีบบรรทัดลงมาเท่านั้นครับ :)

Sorry, comments for this entry are closed at this time.