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,
Most times (?) we don’t want that. But sometimes we do.
! method will change the object, allows us to choose the correct version.
! 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.
false if saving failed, while
ActiveRecord::Base#save! raises an exception.