16

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
  • 165,429
  • 45
  • 277
  • 381
bpereira
  • 966
  • 2
  • 11
  • 29
  • 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

31
length = sentence.length
sentence.each_char.with_index(1){|char, i|
  if i == length
    ...
  end
}
sawa
  • 165,429
  • 45
  • 277
  • 381
17

You are looking for 'with_index' option

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