0

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
3
  • If all equal then what to return ? Commented Mar 25, 2014 at 8:52
  • @ArupRakshit: The idea is to start comparing from the beginning and stop and return index when not the same, if all the values are the same then return nil Commented Mar 25, 2014 at 8:56
  • @MarkV what practical application do you have for such a function? Commented Mar 25, 2014 at 11:47

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

5 Comments

Instead of using the check against siz you could just do array.each_index[0..-2]
@TomFenech Same I am also thinking here in my desk. Again I am thinking if it would be Rubyish idea or not.. :-)
@TomFenech that should be array[0..-2].each_index BTW.. :)
Duly noted! Either way, shouldn't the check against siz be before the comparison so that it short-circuits the && rather than comparing against a nil?
@TomFenech Humm.. That's a Good idea.. Indeed
0
[[1.5,"cm"],[1.5,"cm"],[1.5,"m"]]
.each_cons(2).with_index(1).find{|(a, b), i| a == b}.last
# => 1

1 Comment

...but what does it mean?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.