如何强制 Ruby 字符串为 n 个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14714936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:43:33  来源:igfitidea点击:

How to force Ruby string to n characters

rubystringvariablesstring-length

提问by Paul

How to force Ruby string variable output using putsto n characters so that if the variable is longer, it will be truncated, if shorter, it will be expanded by trailing or leading spaces?

如何使用putsn 个字符强制 Ruby 字符串变量输出,以便如果变量较长,它将被截断,如果较短,它将通过尾随或前导空格进行扩展?

Is there some standard method to do this?

是否有一些标准方法可以做到这一点?

回答by the Tin Man

Ruby supports using format strings, like many other languages:

Ruby 支持使用格式字符串,就像许多其他语言一样:

[11] (pry) main: 0> '%3.3s' % 'f'
=> "  f"
[12] (pry) main: 0> '%3.3s' % 'foo'
=> "foo"
[13] (pry) main: 0> '%3.3s' % 'foobar'
=> "foo"

If you want to pad on the right, use a -in the format string:

如果要在右侧填充,请-在格式字符串中使用 a :

[14] (pry) main: 0> '%-3.3s' % 'f'
=> "f  "
[15] (pry) main: 0> '%-3.3s' % 'foo'
=> "foo"
[16] (pry) main: 0> '%-3.3s' % 'foobar'
=> "foo"

You could also use printfor sprintf, but I prefer the more generic %, which is like sprintf.

你也可以使用printfor sprintf,但我更喜欢更通用的%,就像sprintf.

From the sprintfdocs:

sprintf文档:

  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.

and:

和:

-        | all           | Left-justify the result of this conversion.


What if I want to pad not with spaces but with some other character?

如果我不想用空格而是用其他字符填充怎么办?

The underlying Ruby code is written in C, and it's hard-coded to use ' 'as the pad character, so that's not possible directly, unless you want to modify the source, recompile your Ruby, and live with a one-off version of the language. Instead, you can do something like:

底层的 Ruby 代码是用 C 编写的,它被硬编码' '用作填充字符,因此不能直接使用,除非您想修改源代码、重新编译 Ruby 并使用该语言的一次性版本. 相反,您可以执行以下操作:

[17] (pry) main: 0> ('%-3.3s' % 'f').gsub(' ', '.')
=> "f.."

This gets a lot more complicated than a simple gsubthough. Often it's better to adjust the string without using format strings if you need to supply special characters. Format strings are very powerful but they're not totally flexible.

不过,这比简单的要复杂得多gsub。如果您需要提供特殊字符,通常最好在不使用格式字符串的情况下调整字符串。格式化字符串非常强大,但它们并不完全灵活。

Otherwise, I'd go with something like @steenslag's solution, which is the basis for rolling your own. You lose the ability to use format strings and have to rely on concatenating your strings or something similar to get columnar output, but it will also work.

否则,我会采用类似@steenslag 的解决方案,这是滚动您自己的解决方案的基础。你失去了使用格式字符串的能力,必须依靠连接你的字符串或类似的东西来获得柱状输出,但它也可以工作。

回答by MiGro

To make a string a fixed length shorter:

要使字符串固定长度更短

  str_var.slice(1..10)

To make a string a fixed length longer:

要使字符串固定长度更长

  str_var.ljust(10, ' ')

They could be combined into something like:

它们可以组合成类似的东西:

  (str_var.length > 10) ? str_var.slice(1..10) : str_var.ljust(10, ' ')

Where str_varis, of course, your string

str_var当然,你的字符串在哪里

回答by steenslag

class String
  def fix(size, padstr=' ')
    self[0...size].rjust(size, padstr) #or ljust
  end
end

p 'lettersletters'.fix(9) #=> "lettersle"
p 'letters'.fix(10, '.')  #=> "...letters"

Combines the slicemethod (the []) with rjust.

slice方法([])与rjust.

回答by superluminary

For a pure Ruby one liner you might do this:

对于纯 Ruby one liner,您可以这样做:

(str + ' ' * length)[0,length]

Which will yield:

这将产生:

str = "Hello"
length = 10
=> "Hello     "

or:

或者:

str = "Hello"
length = 2
=> "He"

回答by Kormie

If you're talking about a method to truncate strings I would check out ActionView::Helpers::TextHelper#truncate

如果您在谈论截断字符串的方法,我会查看ActionView::Helpers::TextHelper#truncate

From the examples:

从示例中:

truncate("Once upon a time in a world far far away")

# => Once upon a time in a world...