为什么我不能修改的方法数组的值? [英] Why can't I modify values of an array in a method?

查看:177
本文介绍了为什么我不能修改的方法数组的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的code片段,数组甲板应该等于 [6,9,5,6,5,1,2 ] ,因为红宝石按引用传递数组。方法调用后,甲板上的值不会改变。这是为什么?

In the code fragment below, the array deck should equal [6,9,5,6,5,1,2] since Ruby passes arrays by reference. After the method call, the values of deck does not change. Why is that?

def count_cut!(deck)
  s1, s2 = deck[0, deck.last], deck[deck.last..-2]
  deck = s2 + s1 + [deck.last]
end

deck = [5, 1, 6, 9, 5, 6, 2]
count_cut!(deck)
p deck

我使用Ruby 1.9.2-P180。

I am using Ruby 1.9.2-p180.

推荐答案

分配到甲板不变异中传递数组中。这是像对待一个局部变量在函数定义的范围。您可以拨打 deck.replace 如果你真的想变异它。

Assigning to deck does not mutate the array that was passed in. It is treated like a local variable in the scope of the function definition. You can call deck.replace if you really want to mutate it.

这篇关于为什么我不能修改的方法数组的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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