Ruby 是按引用传递还是按值传递? [英] Is Ruby pass by reference or by value?

查看:63
本文介绍了Ruby 是按引用传递还是按值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@user.update_languages(params[:language][:language1], 
                       params[:language][:language2], 
                       params[:language][:language3])
lang_errors = @user.errors
logger.debug "--------------------LANG_ERRORS----------101-------------" 
                + lang_errors.full_messages.inspect

if params[:user]
  @user.state = params[:user][:state]
  success = success & @user.save
end
logger.debug "--------------------LANG_ERRORS-------------102----------" 
                + lang_errors.full_messages.inspect

if lang_errors.full_messages.empty?

@user 对象向 update_lanugages 方法中的 lang_errors 变量添加错误.当我对 @user 对象执行保存时,我丢失了最初存储在 lang_errors 变量中的错误.

@user object adds errors to the lang_errors variable in the update_lanugages method. when I perform a save on the @user object I lose the errors that were initially stored in the lang_errors variable.

虽然我试图做的更像是一种黑客攻击(这似乎不起作用).我想了解为什么变量值被洗掉了.我理解通过引用传递,所以我想知道如何将值保存在该变量中而不会被清除.

Though what I am attempting to do would be more of a hack (which does not seem to be working). I would like to understand why the variable values are washed out. I understand pass by reference so I would like to know how the value can be held in that variable without being washed out.

推荐答案

在传统术语中,Ruby 是严格按值传递的.但这并不是你在这里真正要问的.

In traditional terminology, Ruby is strictly pass-by-value. But that's not really what you're asking here.

Ruby 没有任何纯非引用值的概念,因此您当然不能将一个值传递给方法.变量总是对对象的引用.为了获得一个不会从你身下改变的对象,你需要复制或克隆你传递的对象,从而提供一个其他人无法引用的对象.(尽管这也不是万无一失的——两种标准克隆方法都进行浅拷贝,因此克隆的实例变量仍然指向原始对象所做的相同对象.如果 ivars 引用的对象发生变异,那将仍然出现在副本中,因为它引用了相同的对象.)

Ruby doesn't have any concept of a pure, non-reference value, so you certainly can't pass one to a method. Variables are always references to objects. In order to get an object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to. (Even this isn't bulletproof, though — both of the standard cloning methods do a shallow copy, so the instance variables of the clone still point to the same objects that the originals did. If the objects referenced by the ivars mutate, that will still show up in the copy, since it's referencing the same objects.)

这篇关于Ruby 是按引用传递还是按值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆