0

I run into a lot of situations where I'm modifying a variable with a method and setting it to that modified value e.g...

value = "string"
value.modify #=> "new string"
value #=> "string"
value = value.modify
value #=> "new string"

I noticed that many Ruby methods have a value.modify! varient that does just that.

Is there a shorthand in Ruby for doing value = value.modify? Also if I was ever to make my own modify! method how would I go about implementing it?

2
  • 2
    IMO, functional style programming where methods do not mutate the object is preferable in general, and writing out var = var.method or similar isn't all that bad. There are bigger, worse code issues to worry about. Commented Jul 8, 2012 at 1:41
  • Ya, I could see how this could be a problem when debugging. Commented Jul 8, 2012 at 20:24

1 Answer 1

2

It really depends on how the class is implemented. These bang-methods are not really possible on immutable objects like Symbols or Fixnums. For Enumerables like Arrays, there is a replace() method that lets you write any bang-method like this:

def bang()
  replace(this.non_bang)
end

If you look at the source of many bang-methods, you will see that normally the bang-methods contain the meat of the code and the non-bang methods simply call dup() or clone() on the object and then call the bang version of the method like this:

def non_bang(*args)
  clone.bang(*args)
end
Sign up to request clarification or add additional context in comments.

2 Comments

Enumerables do not necessarily have a replace method, but strings do, so that might be useful to the OP.
Ahh good call, I know Strings and Arrays have replace() and just assumed it was everywhere.

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.