문제

I have a header method that write a standard header to all text files I throw it's way. Here's the code:

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

So when I run the following call statement:

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

I get the following error:

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>'

Line 63 is this line:

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

What am I doing wrong?

도움이 되었습니까?

해결책 2

If you want to do string padding, which it seems you're doing here, why not use the sprint notation?

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

This uses the String#% method. The %-70s means pad string to 70 spaces, left aligned. Without - it is right aligned.

Any values that are too long will overflow this spot. To handle that:

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

That should limit it to the first 70 characters. Within the Rails environment there's a method called truncate that can add on an ellipsis to show truncation occurred.

다른 팁

The problem is your description is longer than 70 characters and so you're multiplying the string by a negative value, which is not allowed.

To fix it change the line with the error to this:

out.puts "| " + description.to_s + " " * [0, (70-description.length)].max + "|"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top