Argument Option

  • 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.

ตัวอย่างการใช้ Argument ใน ruby

def create_car( model, convertible=false)
  ...
end

เราสามารถเรียกใช้ create_car โดยส่งตัวแปรให้เพียงตัวเดียวหรือสองตัวก็ได้

create_car('sedan')
create_car('sports car', true)
create_car('minivan', false)

กรณีที่ method ถูกเรียกโดยส่งค่าให้เพียงตัวแปรเดียว method จะกำหนดค่า false ให้ convertible โดยอัตโนมัติครับ

argument ที่มีค่ากำหนดไว้แล้วต้องเรียงอยู่หลังสุดนะครับ

method ของ ruby ทำให้เรากำหนด argument ใด้ flexible มากๆ เช่น

  def add_students(*names)
    for student in names
      puts("adding student #{student}")
    end
  end
 
  add_students( "Fred Smith", "Bob Tanner")

เมื่อเราใส่ * ไว้ท้ายสุด ruby จะแปลงค่าที่อยู่ต่อท้ายเป็น array อย่างในตัวอย่าง ruby จะทำให้

names = ["Fred Smith", "Bob Tanner"]

ลองดูอีกตัวอย่างที่เราใสทั้ง regular arguments และ arguments array ไว้ด้วยกัน

  def describe_hero(name, *super_powers)
    puts("Name: #{name}")
    for power in super_powers
      puts("Super power: #{student}")
    end
  end

ตัวอย่างการเรียกใช้ method hero

describe_hero("Batman")
describe_hery("Flash", "Speed")
describe_hero("Supreman", "can fly", "x-ray vision", "invulnerable")

ย้าย Codenone

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

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