Pointer in Ruby

有些话、适合烂在心里 提交于 2021-01-29 09:20:28

问题


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.

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

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/51844610/pointer-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!