Ruby Ruby Blocks Working With Blocks Blocks in the Wild: Strings and Integers

Evan McCullough
Evan McCullough
5,970 Points

Last iteration through .times?

Hi there,

Is there any easy way to identify the last iteration through .times? I see on Stack Overflow that, for arrays, there is a .each_with_index block, which would sort of do what I am looking for.

Playing around here, I just turned the .each_char block into a "cheer" (Give me a T, Give me an r, etc.). I was wondering if on the last full puts of "Treehouse" I could add more exclamation points, still within 3.times.

# Strings each_char
cheer = "Treehouse"
cheer.each_char do |letter|
  puts "Give me a #{letter}."
end

3.times do
  puts "What's that spell?!?"
  puts cheer + "!"
end

Cheers!

  • Evan

1 Answer

Mike Wittenauer
Mike Wittenauer
10,308 Points

Something like this should work. You can pass the index to the times block. It starts at 0 so once it equals 2 you can print your three "!"

3.times do |i|
  puts "What's that spell?!?"
  if i == 2
    puts cheer + "!!!"
  else
    puts cheer + "!"
  end
end