cnaize cnaize - 19 days ago 11
Ruby Question

SQL-like syntax for array of objects

I have an array of objects. I need to use an SQL-like condition WHERE field like '%value%' for some object fields in this array.
How to do it?

Edited:
For example I have array with

Users
and I need to find all users with
first_name
like
ike
and email
like
123
.

Edited2:
I need method to get
Users
with
first_name
like smth and email like smth from ARRAY of my
Users
.
Users
have
first_name
and
email
.

Edited3:
All my users are in database. But I have some business logic, at the end of this logic I have array with
Users
. Next I need to filter this array with some text:
ike
for
first_name
and
123
for email. How to do it?

Answer
arr = %w[hello quick bool boo foo]
arr.select { |x| x.include?("foo") }
=> ["bool", "boo", "foo"]

or in your case, if you have an array of objects, you can do:

x.first_name.include?("foo") && x.email.include?("123")

For more customization, you can use Array#select with Regexeps

Comments