1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby,実引数、仮引数学び

Posted at
  • 実引数を定義し、それに答える仮引数の値はどんなものでも構わないが、

    仮引数で受け取ったメソッド内では仮引数で使った値を用いてプログラムを組み立てる。

どういう事かというと、

def aaa(input)
  input ** 2
end

bbb_input = 3
puts aaa(bbb_input)

9

大概の例題はこのような形でinputに似通ったものを使っていたりするので、

実引数、仮引数の関係がとてもわかりづらい。
なので、無茶苦茶にしてみる事にした。

def aaa(szxdcrftvgbsdfghdfghjdxfghldcfvgkml)
  bbb_input ** 2
end

bbb_input = 3
puts aaa(bbb_input)

111.rb:2:in `aaa': undefined local variable or method `input' for main:Object (NameError)

しかしこのままではエラーが出てしまう。

何故エラーが出るかというと、puts aaaはdef~end内で括ったメソッドを呼び出しているに過ぎないからである。

bbb_input = 3を定義し、aaa(bbb_input)とする事でaaaにbbb_input = 3を関連付けさせ、
puts aaaによってdef aaa endで定義したメソッドに仮引数を通じて値を渡し処理を実行しようとしているが、
def aaa end内では実引数が仮引数に変換されて処理をされるのでdef aaa end内の処理は、
仮引数を使って処理を記述しなければならないのである。

最初は非常にわかりにくいが、この仕組みが実はとても便利なのである。

エンジニア初心者のころは数列計算のような形でしか実引数、仮引数を扱わないと思うが、
これが例えば会計アプリを作成するとなった場合、
同じ処理を使いたいが実行結果のみ変えたいとなった時に、
実引数と仮引数が同じ処理を複数作る必要はなく、
その処理を行いたいメソッドに対して実引数さえ乗っけてしまえば、
後は仮引数が自動的に実引数を仮引数に変換してくれるので複数同じ処理を書かなくて済むのである。

先ほどまで記述していたコードで表すと、

def aaa(szxdcrftvgbsdfghdfghjdxfghldcfvgkml)
  szxdcrftvgbsdfghdfghjdxfghldcfvgkml ** 2
end


bbb_input = 3

a = 4

puts aaa(bbb_input)
puts aaa(a)

9
16

この通り"bbb_inpput"も"a"も無事に処理が完了する。
同じ処理はメソッド一つで済むという事である。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?