Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an object with specific property exists in a Ruby array

I have an array of objects *and the object looks something *like this {seat_id, room_id, date_created};
I want to find if in that array there is an object which has seat_id equal to a specific value. How can I do that?

like image 394
gabitzish Avatar asked Jul 07 '12 16:07

gabitzish


People also ask

How do you find if an element exists in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

Is an array an object in Ruby?

What are array methods in Ruby? Array methods in Ruby are essentially objects that can store other objects. You can store any kind of object in an array. You can create an array by separating values by commas and enclosing your list with square brackets.

How do you delete an element from an array in Ruby?

Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.


2 Answers

arr.any?{|a| a.seat_id == "value"} 
like image 77
davidrac Avatar answered Oct 08 '22 00:10

davidrac


Here:

arr.find_index {|item| item.seat_id == other.seat_id} 
like image 23
Linuxios Avatar answered Oct 08 '22 00:10

Linuxios