0

I need to count the number of values that both arrays have.

def process_2arrays(arr1, arr2)
  length1 = arr1.count
  length2 = arr2.count
  arr3 = []
  i = 0
  while length1 >= i do
    ci = arr1[i]
    if arr2.include?(ci)
      arr3 << ci
      damn = arr3.count 
      i = i + 1
    end 

    return [(damn), (2), (3), (4)]
  end
end

When I pass the values to the function it returns [nil, 2, 3, 4] Whats the problem here?

1
  • Unrelated, but please indent your code for legibility. Commented Dec 4, 2015 at 23:11

2 Answers 2

4

To find elements that exist in both arrays, use the set intersection method &.

http://ruby-doc.org/core-2.2.0/Array.html#method-i-26

def count_same_elements(a1,a2)
    (array1 & array2).length
end

Example

count_same_elements([1,2,3,4],[2,3,4,5])
=> 3
Sign up to request clarification or add additional context in comments.

1 Comment

I came to say the same. Best answer. I was going to say (a1 & a2).count, not sure which is better. Nevermind, just looked it up, and length is better: batsov.com/articles/2014/02/17/…
3

damn is initialized within a do .. end block, specifically the while block. Therefore, its value will live within that scope, and when you call the variable outside the block its value is nil.

If you want to preserve the value, you must initialize the variable to nil outside the block.

i = 0
damn = nil
...

As a side note, your code is lacking the most basic Ruby standards. In Ruby you generally use an iterator, not the while. Moreover, you don't use the return at the end of a method.

This is how you would write your method in Ruby using the iterators and taking advantage of some methods from the core library.

def process_2arrays(arr1, arr2)
  arr3 = arr1.select { |e| arr2.include?(e) }
  [arr3.size, 2, 3, 4]
end

Changing completely approach, you can use

def process_2arrays(arr1, arr2)
  (arr1 & arr2).size
end

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.