15

I have this:

sentence.each_char {|char|
   ......
   ......
}

I want this:

sentence.each_char {|char|
   if (char is the last char)
     ......
   end
}

Does anybody know how I can do that?

sawa
  • 160,959
  • 41
  • 265
  • 366
bpereira
  • 928
  • 2
  • 10
  • 26
  • See http://stackoverflow.com/questions/2241684/magic-first-and-last-indicator-in-a-loop-in-ruby-rails for plenty of good ideas. There's no simple, idiomatic way, and the best alternative depends on specifics of your use case. – Jim Stewart Jun 05 '13 at 04:41

2 Answers2

28
length = sentence.length
sentence.each_char.with_index(1){|char, i|
  if i == length
    ...
  end
}
sawa
  • 160,959
  • 41
  • 265
  • 366
16

You are looking for 'with_index' option

sentence.each_char.with_index {|char, index|
  if (index == sentence.length-1)
   ......
  end
}
Chubby Boy
  • 30,682
  • 18
  • 46
  • 47