Update: I'm realizing now my question should be: how do I pass an argument by REFERENCE? I have a clue here: 'pass parameter by reference' in Ruby? but I don't nkow if it's even possible. Might be worth closing this question in fact.
In reference to this previous question: How to reverse a linked list in Ruby
I'm a bit confused why the list isn't reversed in place.
So my expectation would be that:
print_values(node3)
Would initially give:
12 -> 99 -> 37 -> nil
And then when I call: reverse_list(node3)
I would expect a call to print_values(node3)
to give 37 -> 99 -> 12 -> nil
However, I'm instead getting 12 -> nil
To a degree this makes sense because the object referenced by node3 still has a value of 12 and has a next_node of nil, but is there a way to reverse the list completely in place in Ruby?
There seems to be something here about mutability w/r/t ruby that I'm not quite grasping. It's as though with every new addition to the memory stack/function call we get new objects? Some clarification here would be much appreciated.
I've also creatd my own method to try to get the functionality working in place:
def reverse_list(list, previous=nil)
rest_of_list = list.next_node
print "rest of list: "
print_values(rest_of_list)
list.next_node = previous
previous = list
print "new previous: "
print_values(previous)
list = rest_of_list
print "new list: "
print_values(list)
if list.nil?
print "list now nil\n"
list = previous
print "updated list: "
print_values(list)
return list
else
reverse_list(list, previous)
end
end