Joe Essey Joe Essey - 2 months ago 7
Ruby Question

Is there a comparable Array operation to Java's Iterator.hasNext() in ruby?

I can only find methods that look for specific elements of an array.

During my objects.each |a| loop, I want to know when I'm at the final element so I can have a loop like:

objects.each |a|
if objects.hasNext()
puts a.name + ","
else
puts a.name


Iterator's hasNext() determines if the Array's iterator has another element after the one currently being evaluated.

I want to emphasize that I'm looking to print out these values, not turn them in to an Array. .join is not what I'm looking for here.

Answer

It is common that, when leaning a new language, people tend to looking for something that familiar with:)

Your specific questions could easily be solved by using each_with_index.

objects.each_with_index do |object ,index|
    if index == (object.length -1) then 
        puts a.name + ","
    else
        puts a.name
    end
end
Comments