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.rb144 chars8 lines
Output:
main.rb4 chars3 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).
gistlibby LogSnag