Ruby Ruby Loops Ruby Loops The Ruby Loop

Ruby Loop -

  1. What is "fail" method here? How can it be used?
  2. Why there are 3 ends in the codes?
  3. Why repeat method isn't used if we take time to define it?

I give up!

def repeat(string, times)
  fail "times must be 1 or more" if times < 1
  counter = 0
  loop do

Pablo Villegas
Pablo Villegas
2,922 Points
  1. fail raises a Runtime error with the message you pass in (in this case only if times < 1)
  2. A def statement needs an end as well as the loop statement. That is the syntax for ruby
  3. A challenge is a way to practice :) You don't really need this function in practice, you could do n.times.each { puts string } where n is times in the above function and string is the string you want to repeat.