mr_muscle
mr_muscle

Reputation: 2900

How to search in an array of hashes by each character

I've got an array of hashes:

2.6.0 :132 > a = [{:id=>51, :company_name=>"231421AAAAA company"},
{:id=>52, :company_name=>"tregfsd"}, {:id=>53, :company_name=>"aaaaa"},
{:id=>54, :company_name=>"zzzzzz"}, {:id=>55, :company_name=>"bbbbb"}]

How to find data in case when user provide incomplete params like company_name = "231421" it should return

 => {:id=>51, :company_name=>"231421AAAAA company"}

I was trying to use a.detect { |d| d[:company_name] == '231421' } but I've got => nil

What should I use to do search it without giving the whole company_name ?

Upvotes: 0

Views: 66

Answers (2)

spickermann
spickermann

Reputation: 106882

I would use String#start_with?

a.detect { |d| d[:company_name].start_with?('231421') } 

Upvotes: 1

demir
demir

Reputation: 4709

If you want one record:

a.find{ |company| company[:company_name].include?(company_name) }
#=> { :id => 51, :company_name => "231421AAAAA company" }

If you want more than one match record, use select instead of find:

company_name = 'a'
a.select{ |company| company[:company_name].include?(company_name) }
#=> [
#     { :id => 51, :company_name => "231421AAAAA company" },
#     { :id => 53, :company_name => "aaaaa" }
#   ]

Upvotes: 1

Related Questions