Hello,
I'm just starting off with Ruby, but I have a task that landed on my desk that I need a quick answer for, and haven't been able to find a solution online. I appreciate any help I can get.

I need to know if a value in one array appears in another. This should be easy enough with a loop but I'm looking to do it the "Ruby way", if there's such a thing. Here's my current code:

TARGET_COLOR = "red"
# product.color contains "orange, yellow, red", for example
if product.color.any? { |string| string.include?(TARGET_COLOR) }
    #do stuff

Now if I change the first line to TARGET_COLOR = ["red", "green"], I get an error -- I'm guessing the .include? accepts only strings.
What would be the correct syntax/method to search TARGET_COLOR?

Recommended Answers

All 6 Replies

What about the set intersection operator &

[1, 3, 5, 7] & [0, 1, 4, 6, 7, 8]  #=> [1, 7]

As John suggests, array intersection will work. If you don't need to know what clashes, this might be faster due to any? stopping as soon as it's fulfilled.

colours = %w{red green blue orange}
targets = %w{yellow black pink red blue}
colours.any? {|colour| targets.include? colour}

And the reason your code wasn't working is that you were calling include?on a string and passing an array. Both string and array have an include? method, string's only accepts strings but array's accepts any object.

I'd add an example but I'm typing on my phone

commented: +1 for effort. On a phone too. +15

Thank you for the replies! Intersection definitely did the trick. Ended up going with

if not (product.color & TARGET_COLOR).empty?

What about if I just needed it to lazy match? Would any? be better? What would that look like?

Like my post perhaps?

Like my post perhaps?

I did! Thumbs up on all your 2 replies and on John_191's, either before I replied or right after, don't remember.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.