I have a List class implemented with a Node class. My #remove! method is as follows:
def remove!(list_item)
find list_item do |i|
if i == nil
return
else
i.pointer = i.pointer.pointer
end
end
end
#find does as I expect, returning the node previous to the one containing the datum searched for. So I expect this to set the previous item’s pointer to the object after the searched-for item, which should remove the current item from the list.
I think this has to do with how block scoping, and that i passed to the block is not directly referencing the object it should while in the block, and thus cannot overwrite the value of its pointer. How can I force this block to alter this value, without explicitly declaring the value beforehand (which defeats the purpose of this block).
The #find method and the ‘#traverse’ method behave as expected, so I figure this block has to be to blame. I am trying to avoid either making the same function call twice, or declaring a throw-away variable, because I’ve taken an interest in functional programming and would like to try it out.
Edit per request:
The full code on github
The #find method
def find(item_to_find, current_item = @sentinel.pointer, previous_item = @sentinel)
if current_item == @sentinel then puts "not found"; return nil end
if current_item.datum == item_to_find
return previous_item
else
find item_to_find, current_item.pointer, current_item
end
end
Your
findmethod never calls the block, it doesn’t store it anywhere, it doesn’t pass it along to another method, it doesn’t do anything at all with the block. It just ignores it. Therefore, yourremove!method is really just