Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何向数组添加指针?_Ruby_Arrays_Pointers - Fatal编程技术网

Ruby 如何向数组添加指针?

Ruby 如何向数组添加指针?,ruby,arrays,pointers,Ruby,Arrays,Pointers,如何向数组添加指针?我读到的所有内容都是通过引用传递的,但在这些情况下显然不是这样。您需要按照下面的方式编写代码,以满足您的需要 test = 'Don\'t display this' ar = [1, 2, 3, 4] ar[0] = test test = 'I want to retrieve this' print ar[0] # 'Don't display this' test是一个局部变量,可以保存任何类型的对象。在第一个赋值中,它包含一个对象,在第二个赋值中,它包含另一个

如何向数组添加指针?我读到的所有内容都是通过引用传递的,但在这些情况下显然不是这样。

您需要按照下面的方式编写代码,以满足您的需要

test = 'Don\'t display this'
ar = [1, 2, 3, 4]

ar[0] = test
test = 'I want to retrieve this'

print ar[0] # 'Don't display this'

test是一个局部变量,可以保存任何类型的对象。在第一个赋值中,它包含一个对象,在第二个赋值中,它包含另一个全新的字符串对象。如果您想使用同一个字符串对象,这是一个选择。

在Ruby中,几乎每个变量实际上都是指向对象的引用/指针。事实上,您一直在使用指针。如果你想像在C语言中那样做指针运算,这在Ruby中是不可能的,那么很遗憾这是不可能的。测试变量通过各种方法进行更改和编辑,包括那些不是我写的方法。我想我只需要编写/别名一个setter,然后每次都在那里设置数组值。。。我希望有一个C指针的解决方案。@Napoleon:你应该在你的问题中提出这个问题。我们不知道您的要求。奥雅纳确实提供了一个有效的解决方案。但它仍然不是“真正的指针解决方案”。但我想这是Ruby的极限了。@staticx你的第一条评论太完美了。
test = 'Don\'t display this'
ar = [1, 2, 3, 4]

ar[0] = test
test.replace 'I want to retrieve this'

print ar[0]