=begin
語法:def 方法名(參數(shù)1,參數(shù)2,。。。)
想要執(zhí)行的動(dòng)作
end
=end
def hello(name)
print("Hello, ", name, ".\n")
end
hello("Ruby") # =>Hello, Ruby.
#可以為參數(shù)指定預(yù)設(shè)值
def hello(name="Ruby")
print("Hello, ", name, ".\n")
end
hello() # =>Hello, Ruby.
hello("Newbie") # =>Hello, Newbie.
#當(dāng)方法中不止一個(gè)參數(shù)時(shí),預(yù)設(shè)值必須從右端的參數(shù)開始指定
def func(a, b=1, c=2) # 有兩個(gè)參數(shù)可以省略,則應(yīng)設(shè)計(jì)成右邊2個(gè)可以省略
.....
end
def area(x, y, z)
xy = x*y
yz = y*z
xz = x*z
(xy + yz + xz)*2
end
p area(2, 3, 4) # => 52