nothing-special-here
nothing-special-here

Reputation: 12578

Ruby add method!(with exclamation mark) to string

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.

Upvotes: 2

Views: 1477

Answers (2)

WarHog
WarHog

Reputation: 8710

There is such method - String#next!

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

Upvotes: 1

d11wtq
d11wtq

Reputation: 35308

Just use the destructive methods already provided by String.

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

Upvotes: 4

Related Questions