Ruby中的指针 [英] Pointer in Ruby

查看:60
本文介绍了Ruby中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用Ruby解决了一些有关链表的任务.这非常有趣,但是需要几行新的操作.因为如果我在某些函数中传递 head 并更改列表的开头,则必须从方法中返回新的 head 并将其重新分配给变量.

I just solved some tasks about linked lists using Ruby. It was very interesting, but it requires a couple of new lines. Because if I pass head in some function, and change the head of the list, I have to return new head from method and reassign it to the variable.

因为如果我有 a 变量并将其传递给方法,则在内部 a 外部重新分配 a 不会改变:

Because if I have a variable and I pass it to method, reassign a inside, outside a dose not changes:

 it "dose not changes if reassign variable in method" do
        a = [1,2]
        def reasign array
            array = [1]
            array
        end
        assert_equal [1], reasign(a)
        assert_equal [1,2], a
    end

我当然可以在 Hash Array 中扭曲列表的 head 并保存此 Hash 我在对象中改变了一些东西.外部变量仍然指向对象.这行得通.但同样需要几行.

Of course I able to warp head of list in Hash or Array and save this Hash thus when I change something in object. The variable outside still pointing on object. And this works. But again requires couple of lines.

it "method changes the data into a object" do
    a = [1,2]
    def change_object object
        object.push 3
        object
    end
    assert_equal [1,2,3], change_object(a)
    assert_equal [1,2,3], a
end

在Ruby中有没有办法使用类似C的指针或类似PHP的引用?

Is there way in Ruby to use C-like pointers or PHP-like references?

推荐答案

在C语言中,所有ruby变量引用本质上都是指针(但不是指向指针的指针).

All ruby variable references are essentially pointers (but not pointers-to-pointers), in C parlance.

您可以更改一个对象(假设它不是不可变的),因此引用该对象的所有变量都将指向同一(现在已更改)的对象.但是更改变量所指向的 对象的唯一方法是直接分配给该变量-每个变量都是一个单独的引用.您不能使用两个名称为单个引用添加别名.

You can mutate an object (assuming it's not immutable), and all variables that reference it will thus be pointing at the same (now mutated) object. But the only way to change which object a variable is referring to is with direct assignment to that variable -- and each variable is a separate reference; you can't alias a single reference with two names.

这篇关于Ruby中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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