Last Updated: February 25, 2016
·
1.849K
· karthikselva

Mischievous of bang operator in ruby

This is a typical ruby programmer's style of overwriting on the same object:

array = [1.2 , 2.7] 
array.map!(&:floor)

This will modify my same object array.

puts array
#=> [1,2]

Similarly, the below code removes nil values from an array :

array = [1 , 2, nil, 3, nil, 5]
new_array = array.compact
puts new_array
#=> [1,2,3,5]

But if we try to use bang operator for compact we will end up with nil for no nil value cases in an array.

array = [1 , 2, 3] # No nil values present
array.compact!
puts array
#=> nil

This can easily escapes from our eyes while debugging the code.

http://ruby-doc.org/core-1.9.3/Array.html#method-i-collect-21

3 Responses
Add your response

My Output :
array = [1 , 2, 3]
=> [1, 2, 3]

> array.compact!
 => nil 


puts array
1
2
3

=> nil

Are you using older version of ruby ?

over 1 year ago ·

He linked to the docs for collect, so I'm assuming that's where he went sideways.

That aside, ! is an operator, but methods with the bang suffix have nothing to do with that.

over 1 year ago ·

! at the end of a method is not an operator, just part of the method signature.

over 1 year ago ·