通過一種方法接收的參數是相同的對象的引用作爲傳遞給它的參數,例如:對象是否可以更改爲不同類的實例?
def object_id_of_param(object)
object.object_id
end
the_object = [1, 2, 3]
the_object.object_id # => 15247020
object_id_of_param(the_object) # => 15247020
如果調用對象的實例方法,該方法從任何修改就地對象參考對象,無論範圍,所有的變量引用單個對象本身修改原地的,如:
def modify_object(object)
object.map! { |n| n + 1 }
end
the_object = [1, 2, 3]
the_object.object_id # => 18047480
the_object # => [1, 2, 3]
modify_object(the_object)
the_object.object_id # => 18047480
the_object.inspect #=> [2, 3, 4]
如果你想要做別的事情到該對象並像的方法無法做到這一點,您可以使用[email protected]_variable_set
來更改它(請參閱ndn's great answer)。
如果您嘗試將其完全更改爲其他類,則不起作用;以下方法不會修改原始對象。它不會將它從Array
變成Time
;它會導致在該方法中新object
變量引用新Time
對象:
def fail_to_modify_object(object)
object = Time.now
end
the_object = [1, 2, 3]
the_object.object_id # => 14554660
the_object.inspect #=> [1, 2, 3]
fail_to_modify_object(the_object)
the_object.object_id # => 14554660
the_object.inspect #=> [1, 2, 3]
翻動Array
對象到一個新的Time
的例子是人爲的,但你的想法。
是否可以將一個由任意數量的變量引用的對象變成另一個類的實例?
閱讀這篇不錯的文章-http://robertheaton.com/2014/07/22/is-ruby-pass-by-reference-or-pass-by-value/並回答這個問題http:// stackoverflow .com/questions/1872110/is-ruby-by-reference-by-value –