2

I have found many resources how to do add "ordinary" method to String.

ie Add custom method to string object

But i haven't found any info how to add "destructive" method with exclamation mark to String class.

Can somebody rewrite this method to "destructive one"?

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

[this example is very simple, i want to add more complex method to String]

I want to achive something like sub and sub! methods.

Community
  • 1
  • 1
nothing-special-here
  • 11,230
  • 13
  • 64
  • 94

2 Answers2

4

Just use the destructive methods already provided by String.

def nextval!
  case self
  when "A"
    replace("B")
  when "B"
    replace("C")
  # etc
  end
end
d11wtq
  • 34,788
  • 19
  • 120
  • 195
1

There is such method - String#next!

a = "foo"
a.next! # => "fop"
puts a  # => "fop"
WarHog
  • 8,622
  • 2
  • 29
  • 23
  • I know. But I writed that code just for example. I want to add more complex method. – nothing-special-here Oct 22 '11 at 15:36
  • For 'destructive' method you should add exclamation mark at the end of name method (that's just a convention) and to make some changes to 'self'. But not all methods with ! at the end are the destructive one, i.e. 'at_exit!', so that mark usually indicates that the method should be used cautiously. – WarHog Oct 22 '11 at 15:45