-1

I want my code to print silly only on one line but instead it prints it like this:

silly
silly
silly

I want this:

silly silly silly 

This is my code:

    def print_silly_name ()
       i = 0
       while ( i < 60 )
         puts "silly"
         i += 1 
       end
    end

    def main
      name = read_string('Please enter your name: ')
      if ( name == "benyamin") or ( name == "jack" )
        puts  " #{name} that is a nice name"
      else 
        puts print_silly_name
      end
    end

    main
kenlukas
  • 3,616
  • 9
  • 25
  • 36
jack
  • 5
  • 2

3 Answers3

0

Your question isn't really clear but I guess you wan't something like that :

def print_silly_name
  puts Array.new(60, 'silly').join(' ')
end

def main
  name = read_string('Please enter your name: ')
  if ( name == "benyamin") || ( name == "jack" )
    puts  " #{name} that is a nice name"
  else 
    print_silly_name
  end
end

main
user11659763
  • 183
  • 8
0

Looking at your code, you have a few issues there:

  1. The main one you mentioned in your question and title is that the name you print comes in a new row for each iteration of the loop. That's because you're using puts but should be using print in your case. You can read more about that here

2.You're calling the #read_string method which isn't defined anywhere in your code. What you want to do is either replace it with gets.chomp More about gets here or define your #read_string method like this:

def read_string
  gets.chomp
end

3.As Stefan mentioned, you're using or which probably isn't what you're looking for here (More about that here) You're better off using the || operator in your case.

Fixing these mistakes brings us to a working version of your code:

def print_silly_name_60_times
  60.times do
    print "silly "
  end
end

def main
  name = gets.chomp
  if ( name == "benyamin") || ( name == "jack" )
    puts  " #{name} that is a nice name."
  else
    print_silly_name_60_times
  end
end

main

After cleaning up a few things and making it a bit more compact, we get:

def print_silly_name_60_times
  60.times{print "silly "}
end

def main
  name = gets.chomp
  %w(benyamin jack).include?(name) ? (puts  " #{name} that is a nice name.") : print_silly_name_60_times
end

main
Viktor
  • 2,623
  • 3
  • 19
  • 28
-2

Use this to print silly 60 times

def print_silly_name () puts "silly "* 60 end

Saif chaudhry
  • 409
  • 3
  • 10