【问题标题】:Error when trying to get the length of a variable in Ruby尝试在 Ruby 中获取变量的长度时出错
【发布时间】:2023-03-26 04:16:01
【问题描述】:

我有一个标头方法,它可以将标准标头写入我抛出的所有文本文件。代码如下:

def header(file, description)
    File.open(file, 'w') do |out|
        out.puts ".------------------------------------------------------------------------."
        out.puts "| File generated by: " + Etc.getlogin() + " " * (52-Etc.getlogin().length) + "|"
        out.puts "| File generated at: " + Time.now().to_s() + "                           |"
        out.puts ".------------------------------------------------------------------------."
        out.puts "| DESCRIPTION:                                                           |"
        out.puts "| " + description.to_s + " " * (70-description.length) + "|"
        out.puts "|                                                                        |"
        out.puts "'------------------------------------------------------------------------'"
        out.puts "=====FINDINGS====="
    end
end

所以当我运行以下调用语句时:

 header('01httpserver.txt', "This file details all configuration files with where http servers are concerned.")

我收到以下错误:

cis.rb:63:in `*': negative argument (ArgumentError)
    from cis.rb:63:in `block in header'
    from cis.rb:57:in `open'
    from cis.rb:57:in `header'
    from cis.rb:70:in `<main>'

第 63 行是这一行:

out.puts "| " + description.to_s + " " * (70-description.length) + "|"

我做错了什么?

【问题讨论】:

    标签: ruby string string-length


    【解决方案1】:

    问题是您的描述超过 70 个字符,因此您将字符串乘以负值,这是不允许的。

    要修复它,将出现错误的行更改为:

    out.puts "| " + description.to_s + " " * [0, (70-description.length)].max + "|"
    

    【讨论】:

    • 是的,做到了。谢谢!
    【解决方案2】:

    如果您想进行字符串填充,看起来您正在这里做,为什么不使用sprint 表示法?

    out.puts "| %-70s|" % description.to_s
    

    这使用String#% 方法。 %-70s 表示将字符串填充到 70 个空格,左对齐。没有-,它是右对齐的。

    任何太长的值都会溢出这个位置。处理:

    out.puts "| %-70s|" % description.to_s[0,70]
    

    这应该限制为前 70 个字符。在 Rails 环境中,有一个名为 truncate 的方法可以添加省略号以显示已发生截断。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2016-10-17
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多