2009-01-08

Searching an array for a value in another array.

Been spending a few minutes (x 30+) trying to figure this one out in a nice manner.
I want to search an array, to see whether a value of another array exists in the first array. This being in Ruby of course.
Here's my solution:
["x", "z"].any? { |value| ["a", "b", "c"].include? value }
Returns false.
["a", "b"].any? { |value| ["a", "b", "c"].include? value }
Returns true.
So, there you have it. This piece of code will return true if one of the values in the first array exists in the second array. Here's a little for google indexing: Find a value in an array, or locate a value in an array.
A true programmer would probably shorten "value" to "v" to make it less legible for the "meagre earthlings", but I'm a "Nice Guy"(tm).
Hope that's of any help to anyone out there.

Updated:
Righto, annoyingly, CT has just got back from "AFK", and trimmed my efforts down to:
(["a", "b"] & ["a", "b", "c"]).empty?
Returns false.
(["z", "x"] & ["a", "b", "c"]).empty?
Returns true.
He could have not AFK'd and helped me when I asked. Eitherhoo... His solution is much neater than mine, and I'm grateful for his help! :) Sweeet!

Updated II:
That's what I get for listening to friends. Eagle eyed readers will spot that CT's solution above returns the wrong boolean value. They should be reversed. Use "!" to do that, like this:
!(["a", "b"] & ["a", "b", "c"]).empty?
Returns true.
!(["z", "x"] & ["a", "b", "c"]).empty?
Returns false.
That should'a done it. :)

No comments: