Home

Ruby Methods

What can the bang (!) refer to in Ruby?

Select one or more answers

Using the bang (!)

From Stack Overflow

In general, methods that end in ! indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to.

foo = "A STRING" # a string called foo foo.downcase! # modifies foo itself puts foo # prints modified foo # 'a string'

In the standard library, there are lots of places where you will see a call with the ! and without. These are referred to as "safe methods", and return a copy of the original with changes applied to the copy.

foo = "A STRING" # a string called foo bar = foo.downcase # doesn't modify foo; returns a modified string puts foo # prints unchanged foo # A STRING puts bar # prints newly created bar # a string

Keep in mind this is just a convention, but a lot of Ruby classes follow it.

Bang is also used for methods that raise an exception when the method without does not, e.g.: save and save! in ActiveRecord.

The exclamation point means many things, and sometimes you can't tell a lot from it other than "this is dangerous, be careful". Other libraries may use it differently. In Rails an exclamation point often means that the method will throw an exception on failure rather than failing silently.

Repository

https://github.com/okeeffed/developer-notes-nextjs/content/ruby/ruby-methods

Sections


Related