1

I have an array of arrays like so: [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]]. I want to check whether the larger array contains arrays of a given number without regard to the animal element of the array. I also do not want to loop through the array because this would become computationally heavy.

So something like @boolean = bigArray.include?([2, *]), except something that actually works...

2
  • 1
    Whether explicit or implicit, one way or another, you're looping. There is no magic way of stepping through an array and examining each element without a loop. If you are that concerned with performance, you've chosen the wrong container for your data. Commented Sep 24, 2012 at 20:19
  • Also, you've given us a test case where the keys are duplicated but not told us what you expect to happen. Should your bigArray.include... return [2, "cat"], or should it return ["cat", "bird"], or what? Commented Sep 24, 2012 at 20:21

3 Answers 3

4

You have two possible solutions. Detect the element in the array or convert the array into a Hash

1. Use Enumerable#detect, it will stop as soon as it finds a match and return it, nil otherwise.

> a = [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]]
 => [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]] 
> a.detect{ |(n, _)| n == 2 }
 => [2, "cat"]
> a.detect{ |(n, _)| n == 10 }
 => nil 

If you want to add this to the Array class like your example, and force it to return a boolean, do this:

class Array
  def custom_include?(num)
    !!detect{ |(n, _)| num == n }
  end
end

Example:

> a.custom_include?(2)
 => true 
> a.custom_include?(10)
 => false

2. If you don't care about the colliding keys, you could convert the array into a Hash and see if the key exists.

> a = [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]]
 => [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]] 
> Hash[a][2]
 => "bird"
> Hash[a][10]
 => nil
Sign up to request clarification or add additional context in comments.

Comments

0

One very simple way that doesn't involve looping is to convert the structure to a hash. Your arrays happen to be in an ideal format for this:

values = [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]]

Hash[values][2] # "bird"

You will lose the first value for each key, but it will serve to show whether a key exists.

Comments

0

We can use this:

arr = [[1, "dog"], [2, "cat"], [2, "bird"], [3, "monkey"]]
arr.assoc(2)

it will return [2, cat]

in array if element is not exist

arr.assoc(10)

returns nil

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.