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

时间:2011-10-22 15:28:11

标签: ruby methods

我发现很多资源如何为String添加“普通”方法。

Add custom method to string object

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

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

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

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

我希望获得类似subsub!方法的内容。

2 个答案:

答案 0 :(得分:4)

只需使用String提供的破坏性方法。

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

答案 1 :(得分:1)

有这样的方法 - String#next!

a = "foo"
a.next! # => "fop"
puts a  # => "fop"
相关问题