Finding an element in an array of hashes

A

Alex Stupakov

Hi,

I have an array of Facebooker::User objects

so friends.class = Array
and friends[1].class = Facebooker::User

Facebooker::User objects which are basically hashes.

each friend has a unique facebook_id so
friends[1].facebook.id.class = Integer

I'd like to find the array member with a particular facebook_id.

friends.find_by_id(12345) should return the corresponding
Facebooker::User object

What's the cleanest way to do this?
Do I have to iterate over the array members or is there a method in Ruby
that does this?

Thanks

Alex
 
A

Aldric Giacomoni

Alex said:
Hi,

I have an array of Facebooker::User objects
so friends.class => Array
and friends[1].class => Facebooker::User

Facebooker::User are objects which are basically hashes.
friends[1].facebook.id.class => Integer

I'd like to find the array member with a particular facebook_id.
friends.find_by_id(12345) should return the corresponding
Facebooker::User object

What's the cleanest way to do this?
Do I have to iterate over the array members or is there a method in Ruby
that does this?

"basically" hashes? That doesn't look like hash syntax to me..

friends.find { |friend| friend.facebook.id = 12345 }

http://ruby-doc.org/core/classes/Enumerable.html#M003122
 
A

Alex Stupakov

Aldric said:
"basically" hashes? That doesn't look like hash syntax to me..
You're right, my mistake.
Thanks for the suggestion, it works great, and for the link.
 
J

Jesús Gabriel y Galán

Alex said:
Hi,

I have an array of Facebooker::User objects
so friends.class => Array
and friends[1].class => Facebooker::User

Facebooker::User are objects which are basically hashes.
friends[1].facebook.id.class => Integer

I'd like to find the array member with a particular facebook_id.
friends.find_by_id(12345) should return the corresponding
Facebooker::User object

What's the cleanest way to do this?
Do I have to iterate over the array members or is there a method in Ruby
that does this?

"basically" hashes? That doesn't look like hash syntax to me..

friends.find { |friend| friend.facebook.id = 12345 }

Careful, there should be a == there...

Jesus.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top