Reputation: 329
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?
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]
.
I receive the error comparison of fixnum nil failed
. - How can I resolve this?
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
Upvotes: 0
Views: 173
Reputation: 1939
def filtered_index(array,n)
array.each_with_index{|e,i| puts i if e > n}
end
Upvotes: 0
Reputation: 37409
When you are iterating over an array using each
the x
denotes the value of the item, not its position:
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
:
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
Upvotes: 1
Reputation: 369458
You want to select all elements whose index is less than themselves. You can just say exactly that in Ruby:
a.select.with_index {|el, idx| idx < el }
or even
a.select.with_index(&:>)
Upvotes: 2