【问题标题】:Print loop results on the same line instead of a new line for each iteration在同一行而不是每次迭代的新行上打印循环结果
【发布时间】:2019-08-27 20:06:49
【问题描述】:

我希望我的代码仅在一行上打印silly,而是像这样打印它:

silly
silly
silly

我想要这个:

silly silly silly 

这是我的代码:

    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

【问题讨论】:

  • 你想使用print,而不是puts
  • 您应该使用|| 而不是or。后者是一个控制流操作符,可能不是你想要的。

标签: ruby


【解决方案1】:

你的问题不是很清楚,但我想你不想这样:

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

【讨论】:

  • 这甚至不打印任何东西。你只是在制作一个字符串
  • 我知道^^我适应了它的使用功能:puts print_silly_name
【解决方案2】:

查看您的代码,您有一些问题:

  1. 您在问题和标题中提到的主要内容是,您打印的名称对于循环的每次迭代都会出现在新行中。那是因为您使用的是puts,但在您的情况下应该使用printYou can read more about that here

2.您正在调用 #read_string 方法,该方法未在代码中的任何位置定义。您想要做的是将其替换为 gets.chomp More about gets here 或像这样定义您的 #read_string 方法:

def read_string
  gets.chomp
end

3.正如 Stefan 所提到的,您正在使用 or,这可能不是您在此处寻找的 (More about that here) 在您的情况下,您最好使用 || 运算符。

修复这些错误后,我们将获得您的代码的工作版本:

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

在清理了一些东西并使其更紧凑之后,我们得到:

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

【讨论】:

    【解决方案3】:

    用这个傻傻地打印 60 次

    def print_silly_name () puts "silly "* 60 end

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多