3

Can I check include? at least one element in array with ruby on rails?? Here my example:

a = 1234
b = [1,5,6,7,8....]
if a.include?b[0] == true
   app => return true
if a.include?b[0] == true and a.include?b[1] == false and a.include?b[2] == false and ......
   app still return true

In the real app, I can't call b[0],b[1],b[2]... like that,So, how can I do to check include? at least one element in array, in rails app? Please help me :)

1
  • you want to check if b has an element that == to a right ? Commented Feb 9, 2015 at 10:13

3 Answers 3

3
a1 = a.to_s.chars.map(&:to_i)
# => [1, 2, 3, 4] 
b.any? {|i| a1.include?(i) }
# => true

UPDATE:

Ruby 2.4 has an Integer#digits. So you can do

a1 = a.digits
b.any? {|i| a1.include?(i) }
Sign up to request clarification or add additional context in comments.

Comments

3

In cases like these, basic set algebra comes in handy. In your case, you want to check if the intersection of both sets (here implemented as arrays) is not empty, i.e. if they have any elements in common.

In Ruby, you can use the set operations for this:

a = "12345".chars.map(&:to_i)
b = [1,5,6,7,8]

intersection = a & b
has_common_elements = intersection.any?

You can read more about the intersection operator at the Ruby documentation. And while you are at that, you should also read about the union operator too, which complements the the intersection operator.

Comments

0
digits = a.to_s.chars.map(&:to_i)
(digits - b).empty?

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.