On 25/05/2009, at 6:23 PM, Robert Scott wrote:
>
> Tim,
>
> I really appreciate the time and thoughtfulness you put in your reply.
> To clarify further from my original question, building from your
> example.
>
> contacts = [{:first_name=>'tim', :last_name=>'rand', :id =
> 1},{:first_name=>'jim', :last_name=>'band', :id =>
> 2},{:first_name=>'him', :last_name=>'crand', :id => 3}]
>
# item is a hash, contacts in an array - using the Array#find or
Array#detect method (they're synonymous)
# assuming search_string contains the string you want to find
found_item = contacts.detect{|item| item.values.any?{|value|
value.include?(search_string)}}
or
found_item = contacts.detect{|item| item.values.join.include?
(search_string)}
then, it's simply a matter of getting the id value from the
found_item. As this is a hash, just found_item[:id] should suffice.
Julian.
----------------------------------------------
Learn: http://sensei.zenunit.com/
Last updated 20-May-09 (Rails, Basic Unix)
Blog: http://random8.zenunit.com/
Twitter: http://twitter.com/random8r
> Using a search form, the user will submit a string, looking for a
> particular contact in the array. Unfortunately, this might be just
> "tim"
> or "rand" or "tim rand". If a match is found in the array, I need to
> return the id number associated with the match.
>
>
...
> Unfortunately, I'm not sure how to build the equivalent query for an
> existing array. Sort_by helps, but I haven't found a way to allow it
> to
> search both :first_name and :last_name - only one at a time.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---