`
magixyu
  • 浏览: 81184 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

Ruby Object References

    博客分类:
  • Ruby
阅读更多
When we work with objects in Ruby, we are really working with object references. It is not the object itself we manipulate but a reference to it. When we assign a value to a variable, we are not copying an object "into" that variable; we are merely storing a reference to an object into that variable. Some code makes this clear:

s = "Ruby" # Create a String object. Store a reference to it in s.
t = s      # Copy the reference to t. s and t both refer to the same object.
t[-1] = "" # Modify the object through the reference in t.
print s    # Access the modified object through s. Prints "Rub". 
t = "Java" # t now refers to a different object.
print s,t  # Prints "RubJava".


When you pass an object to a method in Ruby, it is an object reference that is passed to the method. It is not the object itself, and it is not a reference to the reference to the object. Another way to say this is that method arguments are passed by value rather than by reference, but that the values passed are object references.

Because object references are passed to methods, methods can use those references to modify the underlying object. These modifications are then visible when the method returns.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics