在数组上使用Each迭代并返回更大值的索引

时间:2021-09-20 14:26:51
a = [2,2,4,8,9]
ind = 1

a.each do |x|

if a[ind] < a[x]
puts x
end

end

How can I use "each" on an array to iterate over and return the index of all values greater than a certain value in Ruby?

如何在数组上使用“each”迭代并返回Ruby中大于某个值的所有值的索引?

I would like to iterate over the given array a = [2,2,4,8,9]. I want to iterate over the entire array and, using a conditional, put out all values where a[ind] < a[x].

我想迭代给定的数组a = [2,2,4,8,9]。我想迭代整个数组,并使用条件,将所有值放在[ind]

I receive the error comparison of fixnum nil failed. - How can I resolve this?

我收到fixnum nil的错误比较失败。 - 我该如何解决这个问题?

I did try this as well, seting a range for the process:

我也尝试过这个,为这个过程设置一个范围:

    a = [ 2,2,3,4,5]

x = 0
while x >= 0 && x <= 4

a.each do |x|
    if a[1] < a[x]
        puts x
    end

end
x += 1 
end

3 个解决方案

#1


1  

When you are iterating over an array using each the x denotes the value of the item, not its position:

当您使用每个数组迭代数组时,x表示项的值,而不是其位置:

a = [2,2,4,8,9]
ind = 1

a.each do |x|
  if a[ind] < x
    puts x
  end
end
# prints:
# 4
# 8
# 9

Update:

更新:

If you want to print the indexes of the elements with value greater than the value, you should use each_with_index:

如果要打印值大于该值的元素的索引,则应使用each_with_index:

a = [2,2,4,8,9]
ind = 1

a.each_with_index do |x, i|
  if a[ind] < x
    puts i
  end
end
# prints:
# 2
# 3
# 4

#2


2  

You want to select all elements whose index is less than themselves. You can just say exactly that in Ruby:

您希望选择索引小于其自身的所有元素。你可以在Ruby中准确地说出来:

a.select.with_index {|el, idx| idx < el }

or even

甚至

a.select.with_index(&:>)

#3


0  

def filtered_index(array,n)
  array.each_with_index{|e,i| puts i if e > n}
end

#1


1  

When you are iterating over an array using each the x denotes the value of the item, not its position:

当您使用每个数组迭代数组时,x表示项的值,而不是其位置:

a = [2,2,4,8,9]
ind = 1

a.each do |x|
  if a[ind] < x
    puts x
  end
end
# prints:
# 4
# 8
# 9

Update:

更新:

If you want to print the indexes of the elements with value greater than the value, you should use each_with_index:

如果要打印值大于该值的元素的索引,则应使用each_with_index:

a = [2,2,4,8,9]
ind = 1

a.each_with_index do |x, i|
  if a[ind] < x
    puts i
  end
end
# prints:
# 2
# 3
# 4

#2


2  

You want to select all elements whose index is less than themselves. You can just say exactly that in Ruby:

您希望选择索引小于其自身的所有元素。你可以在Ruby中准确地说出来:

a.select.with_index {|el, idx| idx < el }

or even

甚至

a.select.with_index(&:>)

#3


0  

def filtered_index(array,n)
  array.each_with_index{|e,i| puts i if e > n}
end