0

I want a single line of ruby (not using each) that will answer this question: Is there a follower_id of 2397558816 in this array?

myArray = [ #<Follower id: 1, username: "Prep Bootstrap", imageurl: "http://pbs.twimg.com//profile_images/2825468445/2a4...", user_id: "thefonso", follower_id: "2397558816", created_at: "2014-05-21 15:29:03", updated_at: "2014-05-21 15:29:03">, #<Follower id: 2, username: "JAVA Developer", imageurl: "http://pbs.twimg.com//profile_images/2825468445/2a4...", user_id: "thefonso", follower_id: "2352382640", created_at: "2014-05-21 15:29:05", updated_at: "2014-05-21 15:29:05"> ] 

I am convinced that there must be a ruby method or combo of such that can do this. Can this be done?

3
  • Looks like I may have an answer in .any?...ruby-doc.org/core-2.1.1/Enumerable.html#method-i-any-3F Commented May 23, 2014 at 21:46
  • It looks like ActiveRecord association. Is it correct? Commented May 23, 2014 at 21:48
  • You can't do it without iteration, as long as what you have is an array. You can avoid each, but using any?, select, find as in some answers below all uses iteration. If the object is a hash, it is possible. Commented May 24, 2014 at 9:46

3 Answers 3

1

You were on the right way: use Enumerable#any?:

myarray.any? { |v| v.follower_id == 2397558816 } 
Sign up to request clarification or add additional context in comments.

1 Comment

Are you assuming that the (two) elements of MyArray are instances of the class Follower? If they were, wouldn't MyArray look like: => [#<Follower:0x00000101944b50 @id=1,...? Also, if the elements were instances, you wouldn't know if the instance variables had accessors, so I'd think you'd need instance_variable_get.
0

Note: This answer is based on assumption it is an ActiveRecord relation. If it is not, please comment and I'll remove this answer.

This is not a simple array, it is ActiveRecord::Relation object, which is a wrapper around an array. You should almost never use pure array objects on it, as this class is responsible for fetching objects from database. Using any? will fetch all the records from db and then iterate over it searching for match. Instead you should check it on a db lavel to limit number of fetched records (performance):

 relation.exists?(follower_id: 2397558816) 

3 Comments

you "see" what I'm trying to do actually. Let me check this out.
Thanks to all of you, while the other answers work as well, the one given by BroiSatse follows my "intention". Thank you B.
thefonso, are you quite certain that "the other answers work as well"?
0
(myArray.select {|elem| elem.instance_variable_get(:@id) == 1234567}) != [] 

Returns true if the array contains an element with the given id, and false if not

1 Comment

My comment on @mdesantis' answer applies equally here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.