How to check that all elements of one array are larger than their counterparts in a parallel array (in Ruby).

I am trying to compare two arrays to ensure that the corresponding values ​​of one are always greater than the others.

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

# a[0] > b[0] ... a[x] > b[x]

At this point, I am thinking of using injectwith an index and returning if the comparison fails, for example:

b.each_with_index.inject(true) do |cmp, (element,index)|
  if element > a[index] do
    cmp = false
    return
  end
end

Is there a better way to do this? A feeling similar to Ruby or Rails may already have something like this inline, and I skipped it.

+4
source share
2 answers

This is what I would do:

 a.zip(b).all? { |a, b| a > b }

Note that it zipwill be truncated if the two arrays do not have the same size.

+8
source

, , , :

(0...a.length).all?{ |i| a[i] > b[i] }
 #=> true

:

(0...a.length).all?{ |i| a[i] > [b[i], c[i], d[i]].max }

zip range, a b, n = 5_000.

, a[0] < b[0] false:

             user     system      total        real
zip:     0.350000   0.000000   0.350000 (  0.351115)
range:   0.000000   0.000000   0.000000 (  0.000509)

, a[n-1] > b[n-1] false:

             user     system      total        real
zip:     0.760000   0.000000   0.760000 (  0.752424)
range:   0.420000   0.000000   0.420000 (  0.421132)

[ script]

zip ( ), , n.

, zip Ruby, , , .

+5
source

Source: https://habr.com/ru/post/1532945/


All Articles