Ruby tips and tricks

Bang methods

(Exclamation point at the end of the method name)

There are methods that have a permanent or dangerous version. The exclamation point designates to use the dangerous version of the method.

String manipulation

The bang versions of the string manipulation methods (with the exclamation point), modify the string variable in place. Some of these methods are

  • sub
  • gsub
  • reverse
  • sort

The original string ‘gsub’ substitution method:

original = 'My old cat'
new = original.gsub('old', 'new')

results:
original = 'My old cat'
new ='My new cat'

The dangerous (bang) ‘gsub’ method with the exclamation point modifies the original variable:

original = 'My old cat'
original.gsub!('old', 'new')

results:
original = 'My new cat'

Kernel::exit

The script exits with Kernel::exit, but Kernel::exit! causes an immediate exit, bypassing any exit handlers.

 

Leave a comment

Your email address will not be published. Required fields are marked *