HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

Why are exclamation marks used in Ruby methods?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arewhyusedmethodsrubymarksexclamation

Problem

In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a true/false.

But why do some methods have exclamation marks (!) where others don't?

What does it mean?

Solution

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. Here's a simple example for strings:

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


This will output:

a string


In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the ! and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !:

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


This outputs:

A STRING
a string


Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.

Code Snippets

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

Context

Stack Overflow Q#612189, score: 755

Revisions (0)

No revisions yet.