M
M
Max2016-03-02 20:47:48
ruby
Max, 2016-03-02 20:47:48

How to check array elements (Ruby)?

Hello, you need to iterate over the elements of the array, and if the element on the right is greater than the element on the left, display a message that this element is greater than the previous one. My program correctly detects only the first two elements correctly.

a=[11,22,31,224,44,10,20].each_with_index { |val,index| 
   if val[index] > val[index-1]
   	puts "Элемент #{index} больше левого соседа" 
   else 
   	puts "Hello"
   end
}

Please tell me what needs to be corrected.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Yarikov, 2016-03-02
@maxprof

a = [11, 22, 31, 224, 44, 10, 20]

a.each_index do |index| 
  if a[index] > a[index-1]
    puts "Элемент #{index} больше левого соседа" 
  else 
    puts "Hello"
  end
end

A
Alexey P, 2016-03-02
@ruddy22

[11,22,31,224,44,10,20].each_with_index { |val,index| puts "Элемент #{index} больше левого соседа" if val[index] > val[index-1]}

Yes, that should also work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question