ruby - 更改字符串的特定索引,必要时进行填充

标签 ruby string

我有一个名为 indicators 的字符串,该应用程序的原始开发人员用它来存储单个字符来指示模型的某些组件。我需要更改字符串中的第 7 个字符,我尝试使用以下代码来完成此操作:

indicators[6] = "R"

我很快发现问题是字符串并不总是 7 个字符长。例如,我有一组带有 U 2 的值,我需要将其转换为 U 2 R (在 2 之后添加一个额外的空格)。有没有一种简单的方法可以用 Ruby 强制进行字符计数?

最佳答案

使用String.ljust(integer, padstr=' ')

If integer is greater than the length of [the receiver], returns a new String of length integer with [the return value] left justified and padded with padstr; otherwise, returns [an unmodified version of the receiver].

indicators = indicators.ljust(7)
indicators[6] = "R"  

关于ruby - 更改字符串的特定索引,必要时进行填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30718309/

相关文章:

ruby - 在 Ruby 中生成质数 (Codewars kata : Primes in numbers)

ruby - 在 Rails Admin 中配置正确的连接列

c - 返回 char* 以在 C 中打印

java - 创建字符树

c - 如何按字典顺序对结构中的字符串进行排序?

Ruby:使用字符串动态创建对象

css - OS X 10.11 升级后无法将 sass 转换为 css

ruby-on-rails - 在有 2 个外部表键的情况下,如何按 belongs_to 引用的外部属性排序

c# - 检索(验证)字符串的一部分

常量字符串数组