문제

Ruby 1.8.7

array = [[1.5,"cm"],[1.5,"cm"],[1.5,"m"]]

How to compare each array inside the variable array and see if it is equal, if equal then move on else if not equal then return the index of the array element which was not equal and stop comparing.

So in this example,

array[0] == array[1] 
#=> true

Thus, move on

array[1] == array[2]
=> false

Hence return index i.e = 1

return 1
도움이 되었습니까?

해결책

Here is how I would do using Array#each_index :

def compare_array_elements(array)
  siz = array.size - 1
  array.each_index { |i| return i if i != siz && array[i] != array[i+1] }
  nil
end

array = [[1.5,"cm"],[1.5,"cm"],[1.5,"mm"]] 
compare_array_elements(array) # => 1

array = [[1.5,"cm"],[1.5,"cm"],[1.5,"cm"]]
compare_array_elements(array) # => nil

다른 팁

[[1.5,"cm"],[1.5,"cm"],[1.5,"m"]]
.each_cons(2).with_index(1).find{|(a, b), i| a == b}.last
# => 1
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top