Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created August 8, 2023 09:37
Show Gist options
  • Save gtchakama/48905f75b39ab5b11083df48d50e540a to your computer and use it in GitHub Desktop.
Save gtchakama/48905f75b39ab5b11083df48d50e540a to your computer and use it in GitHub Desktop.
A search filter to an array of objects in Ruby
# Sample array of user objects
users = [
{ id: 1, first_name: "John", last_name: "Doe", age: 30, email: "[email protected]" },
{ id: 2, first_name: "Jane", last_name: "Smith", age: 25, email: "[email protected]" },
{ id: 3, first_name: "Michael", last_name: "Johnson", age: 35, email: "[email protected]" },
{ id: 4, first_name: "Emily", last_name: "Brown", age: 28, email: "[email protected]" }
]
# Function to apply the search filter
def search_users(query, users)
if query.nil? || query.strip.empty?
# If the search query is empty, return the original array
return users
end
search_query = query.strip.downcase
# Filter the array and return only the objects that match the search query
filtered_users = users.select do |user|
# Iterate through all the keys (e.g., first_name, last_name, email, etc.)
# and check if any of the values contain the search query
user.values.any? do |value|
value.to_s.downcase.include?(search_query)
end
end
filtered_users
end
# Test the search_users function with a search query
search_query = "" # You can search using any keyword
result = search_users(search_query, users)
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment