Traversing a friend graph - the ruby way?

A

Alex Stahl

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)
end
end
end

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?

Thanks,
Alex
 
B

Brian Candler

Alex said:
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)
end
end
end

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
helper method.

def traverse(..)
hi5 = Hi5fbapi.new @api_key, @secret
do_traverse(hi5, ...)
end

def do_traverse(hi5, ...)
..
do_traverse(hi5, ...)
..
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top