Alex S. wrote:
Recently, I needed to write some code to traverse friend graphs on my
website. Due to my C++ background, I used recursion:
def traverse(user, depth, origin=nil)
@hi5 = Hi5fbapi.new @api_key, @secret
if depth > 0
friends = @hi5.get_friends(user)
friends.delete origin if friends.include? origin
depth -= 1
friends.each do |friend|
traverse(friend, depth, user)
But as I continue to learn the finer points of ruby, I can’t help but
think there’s a more ruby-oriented way to do this. Any suggestions?
That’s a perfectly good way to traverse a graph. I’d just say: don’t use
an instance variable (@hi5), use a local variable (hi5) instead.
There is only a single instance variable for your object, so when you
recurse and assign to @hi5, you are stomping on the value set in the
caller. In this particular example it doesn’t matter, but in other
algorithms it would.
Or: if a single Hi5fbapi object could be used by all levels, then just
create one before you start recursing, and then pass it to a recursive
hi5 = Hi5fbapi.new @api_key, @secret
def do_traverse(hi5, …)