0

I am still pretty new to Ruby and coding in general and I have been struggling at this particular task for a while a now. I just wanted to know how to add a function in Ruby within a loop. For example:

def main()
name=read_string("What is your name? ")
if name=="Tom"
    puts "an awesome name"
else
    def print_silly_name(name)
        i=0
        puts name + " is a #{i}"+"name!"
        while i<60
            loop do puts " silly"
                i=i+1
            end

The output should have the word "silly" printed 60 times but I am not sure how to call the loop.

2 Answers 2

2

You first define your method, e.g.:

def print_silly_name(name)
  print "#{name} is a"
  60.times { print " silly" }
  puts " name!"
end

And then you call your method:

def main
  name = read_string("What is your name?")

  if name == "Tom"
    puts "an awesome name"
  else
    print_silly_name(name)
  end
end

Example output:

What is your name?

Bob

Bob is a silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly silly name!

Sign up to request clarification or add additional context in comments.

Comments

1

You must delare the method outside of main():

def print_silly_name(name)
  i=0
  while (i<60)
      puts name + " is a #{i}"+"name!"
      i+=1
  end
end

and than just call it in your .rb file:

print_silly_name('Josh')

1 Comment

Declaring the method outside of main is correct, but your method won't run – Ruby doesn't have a ++ postfix increment operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.