davidb
davidb

Reputation: 8954

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

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?

Upvotes: 14

Views: 16818

Answers (3)

tokland
tokland

Reputation: 67910

You should just write data.join(', '). Anyway, answering your question:

Isn't there any method to find out if the current object is the first or the last one in the iteration?

xs = [1, 2, 3, 4]

xs.each.with_index do |x, index|
  if index == 0
    puts("First element: #{x}")
  elsif index == xs.size - 1
    puts("Last element: #{x}")
  else
    puts("Somewhere in the middle: #{x}")
  end
end

Upvotes: 10

chrispanda
chrispanda

Reputation: 3234

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

Upvotes: 28

Salil
Salil

Reputation: 47542

You can use name==data.last if your array is of unique elements

Otherwise use directly

data.join(', ')

Upvotes: 6

Related Questions