Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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