Big O Notation - Confused with some code

Consider this code:

def itemsinlist(list, item)
    list.each do |x|
        if item == x
            return true
        else
            return false
        end
    end
end

groceries = ["milk", "juice", "tacos"]
puts itemsinlist(groceries, "milk")

#This returns false..... why.....?
#Now consider this code:

def itemsinlist(list, item)
    list.each do |x|
        if item == x
            return true
        end
    end
end

groceries = ["milk", "juice", "tacos"]
puts itemsinlist(groceries, "soup")

#Since "soup" is not in the array, it just returns the WHOLE array..
#obviously I don't want it to return the whole array if my item is not in the list..

#Could someone example to me why these 2 problems are giving me these answers?

I’ve never coded in Ruby, actually :smiley:
But I still see a problem here:

def itemsinlist(list, item)
    list.each do |x|
        if item == x
            return true
        else
            return false
        end
    end
end

This code will return false every time when first array element is not equals to item
It will not check the rest of array in such case

False should be returned only when loop is finished (the whole array was checked and nothing found):

def itemsinlist(list, item)
    list.each do |x|
        if item == x
            return true
    end
    return false
end

Is there any reason that you’re not using Array#inculde?

["milk", "juice", "tacos"].include? "milk"
=> true

["milk", "juice", "tacos"].include? "beer"
=> false

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.