#SoftwareEngineer #SalesforceDeveloper #RubyonRails #Music

Mischeivous bang(!) operator in Ruby

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

array = [1.2 , 2.7] 

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
puts array
#=> nil

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