Search code examples
ruby-on-railsarrayscase-insensitive

Searching thru an array case-insensitivly


I have an Array of different transactions and I need to search thru the array for different names of businesses. I need a search method that can find these 3 names.

#<Transaction:0xdf38664 @id="kZB3Y63qBvSDK5eM8K3ESqQDLbpzEZfj19wje", @account="ODaJY8Jza5cBgj7XDg3euOoR7ogrjeCMQZPed", @amount=189.85, @name="DIRECTV", @meta={"is_risky"=>false, "location"=>{}}, @location=nil, @pending=false, @score={"location"=>{}, "name"=>1}, @type={"primary"=>"place"}, @category=["Service", "Cable"], @category_id="18009000">]

My search right now is this:

@transactions = @user.transactions.find_all { |t| t.name.include? 'comcast') }

But this only finds the name case specifically

The transactions may have names like any of these: "name": "DirecTV"; "name": "directv"; "name": "DIRECTV"

I need a method that will find all 3 of this names with that same name search.

I thought casecmp but that only returns a number not the array item. Unless there is a way to use casecmp to return the transaction array but I dont see how.


Solution

  • If this is an ActiveRecord model with relationships, you should treat it as such for performance purposes

    @user.transactions.where "lower(name) IN (?)", ["comcast", "directv", "somethingelse"]
    

    If it really is an array, you could do

    @user.transactions.find_all {|t| t.name.downcase =~ /comcast|directv|somethingelse/ }