What is Ruby's method with a bang (!)

Understanding Rub’s bang/exclamation mark

Suraj Mishra

--

Originally Published in https://asyncq.com/

Introduction

  • I have been doing Java development for 6+ years of my software developer career.
  • But recently I started learning Ruby and Ruby on Rails.
  • As a Java developer, there are lots of similarities and surprises when I jump on the ruby boat, one of them seeing the exclamation operator.
  • In this blog, we will understand what is the meaning of this exclamation mark in Ruby

Exclamation Mark

  • Methods with an exclamation mark are called bang methods in ruby.
  • The use of exclamation marks mainly tells the programmer that these methods are dangerous and used with caution.
  • Dangerous in the sense that this method will modify the input. Let's see the example.

Using Array Example

#1: We have a numbers array that we would like to reverse.

numbers = [1,2,3,4,5]

numbers.reverse
puts numbers.join(",")
  • In the above example, the reverse operation didn’t modify the actual numbers array because when we print the numbers array it's the same as the input array.
  • But if we want to get the reverse array as result then we have to store it in the variable like below and print.
numbers = [1,2,3,4,5]

reversed_number = numbers.reverse
puts reversed_number.join(",")
  • So basically in the above example reverse method returns the result array without modifying the actual input array or changing the state.
  • Now let's use the reverse with a bang.
numbers = [1,2,3,4,5]
numbers.reverse!
puts numbers.join(",")
  • As we can see bang methods modify the input array itself, thats why ! means use with caution, since its changes the state of input data.
  • Whenever there is a change in state or mutability we have to be extra cautious since as a developer we can make mistakes.
  • Let's check one more example

--

--