LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby】メソッドの引数名を指定する。後ろにつくコロン(:)の意味

Last updated at Posted at 2020-12-15

個人メモです。

メソッドの引数に後ろにコロンのつく変数が指定されている記述の意味について。

▼こういうの
def jadge(x:)

def jadge(x:)
  p "exist x" if x.present?
end

引数の後ろにつくコロンの意味

引数の中で後ろにつくコロンは、変数名を指定している。(キーワード引数と呼ぶ)

通常、引数は渡された順に、第一引数、第二引数、、、に代入されるが、後ろにコロンをつければ、その変数名と合った引数の値を渡すことができる。

特に扱う変数が複数の場合は変数名で指定できるので便利。

コロンで変数名を指定
#関数定義
def jadge(x:, y:)
  p "exist x" if x.present?
  p "exist y" if y.present?
end


#関数実行
jadge(y: false, x: true)
=> "exist x"



▼通常

def jadge(x, y)
  p "exist x" if x.present?
  p "exist y" if y.present?
end

y = false
x = true
jadge(y, x)
=> "exist y"

変数名ではなく、渡した順番で値が入る。

0
0
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
0
0