webdesserts
webdesserts

Reputation: 1023

setting a variable and modifying it in the same statement in Ruby

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?

Upvotes: 0

Views: 66

Answers (1)

Dan Finnie
Dan Finnie

Reputation: 107

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

Upvotes: 2

Related Questions