Bang Methods in Ruby (and Rails)
Today I learned about Bang methods in Ruby.
Methods ending with !
are potentially dangerous, because they update the object they operate on.
➜ irb --sample-book-mode
>> name = "sample_string"
=> "sample_string"
>> name.reverse
=> "gnirts_elpmas"
>> name
=> "sample_string"
>> name.reverse!
=> "gnirts_elpmas"
>> name
=> "gnirts_elpmas"
As we can see above, reverse!
modified name
itself.
Most times (?) we don’t want that. But sometimes we do.
Knowing that !
method will change the object, allows us to choose the correct version.
In Rails, !
methods raise an exception in case of error. Some may prefer this over checking of the return value, when the method will work without error most of the time, and exception is rare.
e.g. ActiveRecord::Base#save
returns false
if saving failed, while ActiveRecord::Base#save!
raises an exception.