Home > database >  RAILS - HOW TO COMPARE VALUES BY ARRAY INDEX
RAILS - HOW TO COMPARE VALUES BY ARRAY INDEX

Time:02-22

I'm new to rails and I was wondering how I compare the first value of array "a" if it is greater than the first value of array "b"?

Example:

a = [1, 2, 3]
b = [3, 2, 1]

How do I check if a[0] is greater than b[0].

CodePudding user response:

You can use standard Ruby comparison operators within your indices.

a = [1, 2, 3]
b = [3, 2, 1]

a[0] > b[0] # => false

CodePudding user response:

Here is another view. You can use first method

a = [1, 2, 3]
b = [3, 2, 1]

a.first > b.first #=> false

CodePudding user response:

Here's a method you could use to compare any 2 arrays, at any given index, and using any operator:

a = [1, 2, 3]
b = [3, 2, 1]

def compare_at_index(arr1, oper_symb, arr2, index)
arr1[index].public_send(oper_symb, arr2[index])
end

compare_at_index(a, :>, b, 0)
#=>  false

compare_at_index(b, :>, a, 0)
#=>  true

compare_at_index(a, :==, b, 1)
#=>  true
  •  Tags:  
  • ruby
  • Related