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?
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: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()orclone()on the object and then call the bang version of the method like this: