Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a record is the first/last one in an iteration?

Tags:

ruby

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?

like image 562
davidb Avatar asked Oct 22 '11 11:10

davidb


People also ask

How to check last iteration of for loop?

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.

How to check if an element is the last element of an array?

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.


1 Answers

in this specific case, data.join(', ') would do, more generally data.each {|d| #do stuff unless d.equal? data.last}

like image 75
chrispanda Avatar answered Oct 20 '22 05:10

chrispanda