Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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