# *argv
def sum(a,b=0,*argv)
sum = a + b
argv.each { |num| sum += num } if argv
return sum
end
p sum(10) # 10
p sum(10,10) # 20
p sum(10,10,10) # 30
p sum(10,10,10,10) # 40
# &block
def def_by_myself(*argv, &block)
block.call(argv)
end
def_by_myself(('a'..'z').to_a) do |n|
puts n.to_s.upcase
end
關鍵字參數
Ruby ver.2.0 加入,參數有key-value 的關係
默認參數:不傳入值,則以默認值替代
**argv:傳入不定長度的關鍵字參數
1234567
def area(x: 0, y: 0, z: 0)
return ((x*y)+(y*z)+(z*x))*2
end
p area(x: 10) # 0
p area(x: 10, y:10) # 200
p area(x: 10, y:10, z: 10) # 600