Ruby 添加方法!(带感叹号)到字符串

标签 ruby methods

我找到了很多资源如何向字符串添加“普通”方法。

Add custom method to string object

但我还没有找到任何信息如何向 String 类添加带有感叹号的“破坏性”方法。

有人可以将此方法重写为“破坏性方法”吗?

def nextval
  case self
  when "A"
    return "B"
  when "B"
    return "C"
  # etc
  end
end

[这个例子很简单,我想向String添加更复杂的方法]

我想实现像 subsub! 方法这样的东西。

最佳答案

只需使用String已经提供的破坏性方法即可。

def nextval!
  case self
  when "A"
    replace("B")
  when "B"
    replace("C")
  # etc
  end
end

关于Ruby 添加方法!(带感叹号)到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7860572/

相关文章:

Ruby:如何在 sprintf 输出中包含 % 符号?

ruby - 使用 FFI 从 Ruby 访问 Cocoa?

java - Java 是 "pass-by-reference"还是 "pass-by-value"?

java - 线程和 RMI 对象

C++ 链接类定义中定义的方法

Java : Method return Issue

ruby - 使用 watir 连接到本地主机时出现问题

ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055)

ruby - File.exists?() 在应该为真时返回 false?

Java printf 为什么在我的方法中格式不正确?