gpt4 book ai didi

Ruby - 按值传递

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:32 25 4
gpt4 key购买 nike

有没有办法在 Ruby 中按值而不是按引用传递对象?例如,

class Person
attr_accessor :name
end
def get_name(obj)
obj.name = "Bob"
puts obj.name
end
jack = Person.new
jack.name = "Jack"
puts jack.name
get_name(jack)
puts jack.name

输出应该是

Jack
Bob
Jack

代替

Jack
Bob
Bob

如有任何帮助,我们将不胜感激。

最佳答案

没有。 ruby passes by reference, not value .

如果需要模拟传值,可以使用Ruby的Object#clone方法。在这种情况下,你会做这样的事情:

def get_name(obj)
new_object = obj.clone
new_object.name = "Bob"
puts new_object.name
end

这会创建一个对象的浅拷贝。换句话说,对象的实例变量被复制,但变量引用的对象没有被复制。如果你需要做一个深拷贝,你可以阅读this Stack Overflow post . Ruby 没有执行深拷贝的单一方法,但该帖子描述了如何使用编码解码 进行深拷贝。

clonedup 的工作方式非常相似,但也有一些不同。根据文档:

Object#clone

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.

Object#dup

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

你可以看看dupclone文档。

编辑

虽然我的回答可能给出了 OP 正在寻找的内容,但就按引用或值传递的语义而言,它并不完全正确。请参阅此页面上的其他答案和评论以进行更多讨论。也可以看看评论里的讨论herethis post获取更多信息。

关于Ruby - 按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com