I’m trying to figure out whether I should avoid looping through arrays this way if I only want its specific sections.
the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots"]
for number in the_count
puts "This is count #{number}"
end
fruits.each do |fruit|
puts "A fruit of type: #{fruit}"
end
Thanks in advance!
Both of the loops you describe will indeed go through all of the elements in the array. What else would they do? If you just want a single item from an array, use
fruits[2], or if you want just part of the array, usefruits.slice(1,3)orfruits.slice(1..3)(the first one returns 3 elements starting from element 1 (i.e. the second one), the second returns elements 1 through 3).