DEV Community

Kasia Ekiert
Kasia Ekiert

Posted on

Bang! methods

Image description

Ruby Bang methods (!) are a naming convention that indicates that a method can be "dangerous" or modify its receiver. For example, downcase! changes the original string to lowercase, while downcase returns a new string. Bang methods are not always destructive, but they usually want to get your attention.
The merge! method is a way to combine two hashes into one, by adding the contents of the second hash to the first one. If the hashes have duplicate keys, the values from the second hash will overwrite the values from the first one.

Ruby on Rails Bang methods (!) are methods that raise an exception when something goes wrong, such as finding a record in the database or saving a model.

Metody Bang w Ruby i w Ruby on Rails to metody, które używamy z wykrzyknikiem.
Co osiągamy poprzez użycie ! ?

  1. Zapisujemy zamiane na obiekcie.
  2. Użycie metody merge! na hashach powoduje powstanie nowego hasha - z dwóch podanych. Jeśli w drugim hashu będą zduplikowane klucze - z pierwszego hasha - zostaną nadpisane (chyba, że zostanie to wcześniej rozwiązane inaczej ;)
  3. W Ruby on Rails użycie ! dodatkowo - sprawdza walidacjami czy dany obiekt może powstać i zwraca nam ewentualne errory.

Top comments (0)