gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中 options.dup 的用途是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:42:35 24 4
gpt4 key购买 nike

浏览 Rails 代码库时,我发现了大量对 options.dup 的引用。

def to_xml(options = {})
require 'builder' unless defined?(Builder)
options = options.dup
....
end

显然 options.dup 正在复制选项散列,但为什么要在这种情况下这样做?

最佳答案

dup 克隆一个对象。当您将对象传递给方法时,任何更改该对象内部状态的内容都将反射(reflect)在调用范围中。例如,试试这段代码:

def replace_two(options)
options[:two] = "hi there"
end

options = { one: "foo", two: "bar" }
replace_two(options)
puts options[:two]

这将打印 hi there,因为 replace_two() 修改了哈希内容。

如果你想避免改变传入的options,你可以在它上面调用.dup,然后对克隆所做的任何改变都不会反射(reflect)出来在调用范围内:

def replace_two(options)
options = options.dup
options[:two] = "hi there"
end

options = { one: "foo", two: "bar" }
replace_two(options)
puts options[:two]

将打印bar。这是遵循 Principle of Least Astonishment 的常见模式.在 Ruby 中,修改参数的方法通常以 ! 后缀命名,以提醒用户它们是破坏性/修改操作。该方法的非 dup 版本应该被称为 replace_two! 以表明这种副作用。

关于ruby-on-rails - Ruby on Rails 中 options.dup 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15681531/

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