ちょっと調べたので書いとく
% ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]
普通
class Sample
def hoge
p "hoge"
end
end
sample = Sample.new
sample.hoge
"hoge"
引数のデフォルト
class Sample
def hoge(a, b=1)
p "a:#{a}, b:#{b}"
end
end
sample = Sample.new
sample.hoge(1, 2)
sample.hoge(1)
sample.hoge
"a:1, b:2"
"a:1, b:1"
`hoge': wrong number of arguments (0 for 1..2) (ArgumentError)
可変長引数
class Sample
def hoge(*args)
p args.join(",")
end
end
sample = Sample.new
sample.hoge
sample.hoge(1, "hoge", {a: 100})
""
"1,hoge,{:a=>100}"
キーワード引数
class Sample
def hoge(a: "aaa", b: "bbb")
p "a:#{a}, b:#{b}"
end
end
sample = Sample.new
sample.hoge
sample.hoge(a: "1", b: "2")
sample.hoge(b: "1", a: "2")
sample.hoge(b: "100")
a:aaa, b:bbb"
"a:1, b:2"
"a:2, b:1"
"a:aaa, b:100"
同名メソッド
class Sample
def hoge
p "hoge"
end
def hoge(i)
p "hoge #{i}"
end
end
ample = Sample.new
sample.hoge
sample.hoge(5)
`hoge': wrong number of arguments (0 for 1) (ArgumentError)