Why does this function not return true implicitly?

Hi,

This function is not implicitly returning true when the test argument “Aa” is passed:

def repeating_letters?(str)
 uniq_str_arr = str.downcase.chars.uniq
 downcased = str.downcase.chars
 uniq_str_arr.each do |val|
     if downcased.count(val) > 1
         true
     end
 end
 false
end

only once i add “return” in front of “true” does it pass my rspec.

Any ideas? I’ve tried googling for this.

Thanks,
Ryan

Hi Ryan,

Good question. Ruby implicitly returns the last statement which in your method is false, so it will always return false. Even though you said true inside your each block, that is not the last statement in the method so Ruby does not return true. To override this implicit return, you will have to use the return keyword.
Another way to approach this if you really want to use the implicit return is to create a Boolean variable that is initialized to false and only changed to true when the condition is met. You then have that variable be your last statement in the method to get the same result.
Hope this provide some insight on how Ruby works with variables!

~Michael Ruan
Alpha Course TA

1 Like

Thanks Michael! I like the idea about the boolean being set conditionally!