Ruby:Argument

From Blognone

Jump to: navigation, search

ตัวอย่างการใช้ 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 ที่มีค่ากำหนดไว้แล้วต้องเรียงอยู่หลังสุดนะครับ</a>

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")