0

Is there a default difference between methods with '!' and without, in ruby?

collect v collect!

flatten v flatten!

and so on..

Charles
  • 48,924
  • 13
  • 96
  • 136
HandDisco
  • 577
  • 1
  • 5
  • 13
  • Yes and no. *Conventionally* they're used for methods that mutate internal state, perform operations that affect external state (e.g., write to a database), handle exceptions differently, etc. But the `!` is just part of the method name. – Dave Newton Jan 14 '14 at 13:57

1 Answers1

2

In ruby the main difference is that, the ! methods are selfish, i.e. they apply the changes to the self object. They return nil, when no changes are done, while the non-! methods create new modified object.

In Rails the difference is that, the ! methods are safe versions of non-! methods, that means the ! methods raises an exception when the code encountered an error during execution, while non-! methods just return error state, usually false condition.

Малъ Скрылевъ
  • 14,754
  • 4
  • 47
  • 62