使用 splat 运算符通过引用块来传递参数 [英] Pass arguments by reference to a block with the splat operator

查看:48
本文介绍了使用 splat 运算符通过引用块来传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎是在使用 splat 运算符通过引用将参数传递给块时复制了参数.

It seems that the arguments are copied when using the splat operator to pass arguments to a block by reference.

我有这个:

def method
  a = [1,2,3]
  yield(*a)
  p a
end

method {|x,y,z| z = 0}
#=> this puts and returns [1, 2, 3] (didn't modified the third argument)

如何通过引用传递这些参数?如果我直接传递数组似乎可以工作,但 splat 运算符在这里会更实用、直观和可维护.

How can I pass these arguments by reference? It seems to work if I pass the array directly, but the splat operator would be much more practical, intuitive and maintainable here.

推荐答案

  1. 在 Ruby 中,当您编写 x = value 时,您正在创建一个新的局部变量 x,无论它之前是否存在(如果它存在,名称只是反弹而原始值保持不变).因此,您将无法以这种方式就地更改变量.

  1. In Ruby when you write x = value you are creating a new local variable x whether it existed previously or not (if it existed the name is simply rebound and the original value remains untouched). So you won't be able to change a variable in-place this way.

整数是不可变的.因此,如果您发送一个整数,则无法更改其值.请注意,您可以更改可变对象(字符串、散列、数组等):

Integers are immutable. So if you send an integer there is no way you can change its value. Note that you can change mutable objects (strings, hashes, arrays, ...):

def method
  a = [1, 2, "hello"]
  yield(*a)
  p a
end

method { |x,y,z| z[1] = 'u' }
# [1, 2, "hullo"]

注意:我已经尝试回答您的问题,现在我的观点是:更新方法或块中的参数会导致代码错误(您没有 参照透明度 不再).如果愿意,返回新值并让调用者更新变量本身.

Note: I've tried to answer your question, now my opinion: updating arguments in methods or blocks leads to buggy code (you have no referential transparency anymore). Return the new value and let the caller update the variable itself if so inclined.

这篇关于使用 splat 运算符通过引用块来传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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