how to select first two elements of an array and loop over them? in ruby

To select the first two elements of an array in Ruby and loop over them, you can use the take method to create a new array with the desired elements, and then use the each method to iterate over them.

Here's an example:

main.rb
# Example array
array = [1, 2, 3, 4, 5]

# Selecting and looping over the first two elements
array.take(2).each do |element|
  puts element
end
144 chars
8 lines

Output:

main.rb
1
2
4 chars
3 lines

In the example above, the take(2) method is used to select the first two elements of the array, which returns a new array containing the selected elements. Then, the each method is called on the new array to loop over each element and print its value.

Note that the original array is not modified by the take method, and the loop will only iterate over the selected elements (1 and 2 in this case).

related categories

gistlibby LogSnag