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?

More than 3 years have passed since last update.

rubyで簡単に基本型と参照型を感じる

Last updated at Posted at 2020-10-25

背景

メソッドの中で引数を変更してもその変更はメソッド外に影響を及ぼさないと思っている人がいますが、違います。
そこで、メソッド外に影響を及ぼす場合と及ぼさない場合をそれぞれ書いてみます。

実行方法

macのターミナルでRubyを起動

   irb

###基本型 メソッドの引数の持つ値が変わらない場合

a=1
def method_primitive(a)
   a=2
end
method_primitive a #2
a #1 #変わってない

###参照型 メソッドの引数の持つ値が変わる場合

temp={}
temp[1]=1
def method_reference(temp)
	temp[1]=2
end
method_reference temp #2
temp[1] #2 #変わっている
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?