Search code examples
rubyreturn-typeimplicit-declaration

Implicit return value scope in Ruby


I'm using a self-defined include? method to examine the difference between explicit and implicit returns. I understand that #each returns the collection iterated on, so I believe that I need to place my true/false implicit returns in the correct place, but when I do I am getting back the collection and I'm not sure what to modify.

def self.include?(array, search_item)
  array.each do |elem|
    if elem == search_item
      true
    end
  end
end

Below are the tests I'm checking, but I'm not understanding how to match the returns correctly. Why are they not matching or how should I understand the scope of the implicit return?

  result = MethodReturns.include?(numbers_array, 4)
  expect(result).to eq(true)

  result = MethodReturns.include?(numbers_array, 7)
  expect(result).to eq(false)

Solution

  • You will want to change to:

    def self.include?(array, search_item)
      array.each do |elem|
        if elem == search_item
          return true
        end
      end
      return false
    end
    

    The reason for this is because the last statement in the method is the return value. In your case you never return false if there is no match. Be sure to add the return when you want to break out and stop the rest of the method execution immediately.