Rushi Patel

June 5, 2024

[Tech][Ruby] Significance of '!' convention

In Ruby, the '!' is known as the "bang". It performs an operation and changes the value of the variable in place, instead of creating a new variable with the changes.

Selecting even numbers from the `num` variable WITHOUT the '!' operator:
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = num.select(&:even?)
puts 'num:' + num.to_s
puts 'even:' + even.to_s

output:
num:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even:[2, 4, 6, 8, 10]
Without '!', it doesn't change the `num` variable; instead, it returns the modified value that we can store in a new variable.

Selecting even numbers from the `num` variable WITH the '!' operator:
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = num.select!(&:even?)
puts 'num:' + num.to_s
puts 'even:' + even.to_s

output:
num:[2, 4, 6, 8, 10]
even:[2, 4, 6, 8, 10]
The '!' modifies the original array `num` in place.

Thus, the bang operator (!) is also known as a "destructive" operation because it modifies the variable, which might be used elsewhere in the code.

The bang operator also has another important use in Rails: handling exceptions. Let's keep it for the another post! Explanation on select, &:, to_s, also for another post.


-------------------
Bonus: 

Guess what will happen in following example:
num = [2, 4, 6, 8, 10]
even = num.select!(&:even?)
puts 'num:' + num.to_s
puts 'even:' + even.to_s
.
.
.
.
output:
num:[2, 4, 6, 8, 10]
even:
The '!' returns nil if no changes were made.



Written by,
Rushi Patel



About Rushi Patel

Keep scrolling or press my profile icon at the top to view all my posts. Happy reading!