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

Rubyの関数引数の参照をC言語の視点で考えてみた。

Posted at

1. Rubyの関数引数の影響範囲について

Rubyの関数はC言語における参照渡しと値渡しの特性を併せ持つ。

1.1. 値渡し的特性

def function(a)
    a = 10
    puts a
end

a = 3
puts a
function(a)
puts a

上記のコードを実行した場合、以下のような結果となる。

3
10
3

関数内での代入はなかったことになる。

1.2. 参照渡し的特性

def function(a)
    a << 4
    p a
end

a = [1,2,3]
p a
function(a)
p a

上記のコードを実行した場合、以下のような結果となる。

[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4]

配列への挿入は関数外にも反映される。

2. C言語のポインタの考えでのRubyの関数引数の解釈

Rubyの関数内では以下のことが言える。
ポインタは変更できない
関数内では変数のポインタを変更することができるが、
関数外にその変更を持ち出すことはできないということである。

2.1. 値渡し的特性について

関数内での値代入、つまり代入される値へのポインタの入れ替えが関数外ではなかったことになる。

2.2. 参照渡し的特性について

関数内で行われているのは配列への値の挿入である。
つまり、変数のポインタを変更するわけではなく、
そのポインタからint型4つ分ズレた位置のポインタに値を代入する。
よって関数外にも関数内での処理が反映される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?