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.

3
  • You'll need to be more specific. You can probably only mutate the things that are exposed publicly, unless you delve into private APIs, which most likely will just come back to haunt you ;) Commented Oct 22, 2011 at 15:31
  • Do you mean you want to change the value of self to "B", "C", etc? Commented Oct 22, 2011 at 15:32
  • Ah, I see what you're after... Commented Oct 22, 2011 at 15:32

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow it works. :) Thanks. +1 and accept(have to wait 4 min..).
1

There is such method - String#next!

a = "foo"
a.next! # => "fop"
puts a  # => "fop"

2 Comments

I know. But I writed that code just for example. I want to add more complex method.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.