Skip to content

Instantly share code, notes, and snippets.

@makoto
Forked from newbamboo/call_by_sharing.md
Last active September 28, 2015 03:58
Show Gist options
  • Save makoto/1381070 to your computer and use it in GitHub Desktop.
Save makoto/1381070 to your computer and use it in GitHub Desktop.
Call By Sharing

厳密にいうとRubyは値を渡している、しかしながらオブジェクトの参照値を渡す場合、例にあったように破壊的なメソッドで参照先を変更することができる。ほかにも例をあげると、Hashの内部を変更した場合、呼び出し元の変数も変更される。

Strictly speaking, Ruby passes by value. However, what Ruby passes is a reference value of an object so that you can modify the object the reference value is pointing with Ruby's destructive method (= methods ending with !). Another example of modifying the caller value is when you modify a Hash value as follows.

>>  a = {b:'c'}
=> {:b=>"c"}
>> def foo(d); d[:b] = 'C'; end
=> nil
>> foo(a)
=> "C"
>> a
=> {:b=>"C"}

よって厳密には「Pass by reference value, Call by sharing」(http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) と呼んだ方が正しいのだが、本書では「オブジェクトを参照で渡す」、といったもう少し抽象的な用語をdRubyとの対比として用 いている。

Technically speaking "Call By Sharing", or "Call By Object Sharing" (http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) is more correct term, but I wil use the word "Pass by reference" as a more generic meaning that is easier to compare with how dRuby works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment