Why won't ruby return a variable in a certain if statement
So I'm doing random challenges on codewars.com and the challenge is:
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
def stray (numbers)
numbers.each do |num|
num != numbers[0] ? return num : next
end
end
def stray2 (numbers)
numbers.each do |num|
if num != numbers[0]
return num开发者_JS百科
else
next
end
end
end
def stray3 (numbers)
numbers.each do |num|
return num if num != numbers[0]
end
end
array = [1,1,1,1,1,2,1,1,1,1,1]
p stray(array)
p stray2(array)
p stray3(array)
when I run the code the stray method always throws a code. other versions work also but what is making that version not work? just want to understand why. Thanks in advance
精彩评论