FAQ: Loops & Iterators - The .times Iterator

This community-built FAQ covers the “The .times Iterator” exercise from the lesson “Loops & Iterators”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Ruby

FAQs on the exercise The .times Iterator

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Is the .times iterator method only available on an integer?

Just going through my already completed Ruby language and I might have discovered something. (Or might not) :nerd_face:

Why can I use “do” with this? Like:

20.times do

puts “Im tired”

end

Im just curious… :thinking:

That’s quite normal looking.

iterator do
    # code
end

Since your code has no parameter we can leave of the ||.

I see, that makes sense thank you.

2 Likes

Hi everyone!

Why is there a space either side of the contents of the curly braces? Thanks

Screenshot 2022-11-26 at 12.15.01

For legibility (readability). The space character (part of the group of whitespace) is ignored so has no effect.

3 Likes

In Ruby, there is no built-in .times method for non-integer objects. The .times method is specifically available on integer objects and is used to iterate a specified number of times.

If you want to iterate over a collection or another type of object, you would typically use a different method or iterator. For example, you might use .each for arrays or other enumerable objects:

arr = [1, 2, 3, 4, 5]

arr.each do |item|
  puts item
end

This would iterate over each element in the array and print it.