# Traversing a friend graph - the ruby way?

**URL:** <https://www.ruby-forum.com/t/traversing-a-friend-graph-the-ruby-way/195099>\
**Category:** Ruby\
**Created:** [September 16, 2010, 8:06pm UTC](https://www.ruby-forum.com/t/traversing-a-friend-graph-the-ruby-way/195099 "2010-09-16T20:06:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![asoto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/58956e/32.png) [@asoto](https://www.ruby-forum.com/u/asoto)\
**Post date:** [September 16, 2010, 8:06pm UTC](https://www.ruby-forum.com/t/traversing-a-friend-graph-the-ruby-way/195099/1 "2010-09-16T20:06:58Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![asoto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/58956e/32.png) [@asoto](https://www.ruby-forum.com/u/asoto)\
**Post date:** [September 16, 2010, 8:56pm UTC](https://www.ruby-forum.com/t/traversing-a-friend-graph-the-ruby-way/195099/2 "2010-09-16T20:56:06Z")

</div>

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