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?
in this specific case,
data.join(', ')would do, more generallydata.each {|d| #do stuffunless d.equal? data.last}