LoginSignup
1
1

More than 5 years have passed since last update.

Rubyのメソッド引数

Posted at

ちょっと調べたので書いとく

% 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)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1