Its a thing that made me thinking several times. In this example I have an array and this array has 10 values that should be seperated by commatas but after the last one there shouldnt be a commata so I used a counter:
data = ["john", "james", "henry", "david", "daniel", "jennifer", "ruth", "penny", "robin", "julia"]
counter = 0
count = data.size
sentence = String.new
data.each do |name|
if counter == (count-1)
sentence += name
else
sentence += "#{name}, "
end
counter += 1
end
But this is so dirty isnt there any method to find out if the current object (in this case "name") is the frist or the last one in the iteration?
Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
in this specific case, data.join(', ')
would do, more generally data.each {|d| #do stuff
unless d.equal? data.last}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With