user3007294 user3007294 - 1 year ago 37
Ruby Question

Compare current element to the remaining in Array (Ruby)

I want to compare the current element inside an iteration to the rest of the elements in the array. I have no issues from the starting point. The issue comes when I am looking to compare the current element to the elements behind it inside the array.

array = [1, 2, 3, 2, 3, 4, 5]


array.each_with_index do |num, index|
break if array[index + 1] == nil
if num > array[index + 1]
puts "#{num} is greater than the #{array[index + 1]}!"
else
puts "#{num} is less than the #{array[index + 1]}!"
end
end


I am looking for something like:

"3 is greater than 1 and 2 but less than 4 and 5"


Any ideas?

Answer Source

I'm assuming you want all of the elements in the array compared, so you could do something like the following, by making use of Array#select:

array = [1, 2, 3, 2, 3, 4, 5]
sorted_array = array.dup.uniq.sort 

array.each do |i|
  greater_than = sorted_array.select { |comp| comp < i }
  less_than = sorted_array.select { |comp| comp > i }

  puts "#{i} is greater than #{greater_than} but less than #{less_than}"
end

You could play with formatting the output, but this would give:

1 is greater than [] but less than [2, 3, 4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
4 is greater than [1, 2, 3] but less than [5]
5 is greater than [1, 2, 3, 4] but less than []