Ruby String tip

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

เวลาเราจัดการกับ String ยาวๆ ใน ruby
เรามักจะใช้คำสั่ง ประมาณนี้

str = <<-EOF
helloworld
EOF

ซึ่งเวลาอยู่ใน method
แล้วเจอ indent เข้าไป
มันจะไม่ค่อยงามเท่าไร

def say
  str = <<-EOF
helloworld
multi-line
  EOF
end

programmer ruby ซึ่งพิศมัยความงามก็หาทางเปลี่ยนไปใช้

def say
  str = <<-EOF.margin
    |helloworld
    |multi-line
  EOF
end

margin ไม่ใช่ method ที่ build-in มากับ ruby
แต่เนื่องจาก class ของ ruby เป็นแบบเปิด
ทำให้เราสามารถ define method ใหม่ๆเพิ่มเข้าไปเองได้

ในกรณีนี้เรา define method margin
เพิ่มลงไปใน class String

class String   
  def margin 
    arr = self.split("\n")             # Split into lines 
    arr.map! {|x| x.sub!(/\s*\|/,"")}  # Remove leading characters 
    str = arr.join("\n")               # Rejoin into a single line 
    self.replace(str)                  # Replace contents of string 
  end 
end

Note: tip จาก หนังสือ The Ruby Way
Note2: การใส่สี syntax highlight เอง นี่มันเหนื่อยเหมือนกันนะ

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น