JP Silvashy
JP Silvashy

Reputation: 48525

Ruby: Seaching a hash for something

I'm using the Highrise API and Ruby wrapper, but my problem is that (besides having a nightmare of a time with the API it self) I want to search a hash that is returned for something:

>> Highrise::Person.find(:all).detect{|p| p.name == 'Brandon'}
=> [#<Highrise::Person:0x102a4d2f8 @prefix_options={}, @attri....

I can do that but obviously detect along with using == will only return a single item and it must be an exact match, what if I want to search for something and it's not a complete match, more like it "contains" the value? Like take for example if I were to omit the "n" at the end of a name like so:

>> Highrise::Person.find(:all).detect{|p| p.name == 'Brando'}
=> nil

Obvously this would return nil but how would I have this return the items that contain "Brando" in the name?

Upvotes: 0

Views: 569

Answers (2)

khelll
khelll

Reputation: 24010

Try select to get all matching elements, also use regular expression instead of equality:

Highrise::Person.find(:all).select{|p| p.name =~ /Brando/i}

Upvotes: 3

frogstarr78
frogstarr78

Reputation: 868

Highrise::Person.find(:all).select{|p| p.name =~ /Brando/}

if you want multiple results.

the same block can be used {|p| p.name =~ /Brando/ } with detect to get one element

Upvotes: 1

Related Questions