patternrubyCritical
Why are exclamation marks used in Ruby methods?
Viewed 0 times
arewhyusedmethodsrubymarksexclamation
Problem
In Ruby some methods have a question mark (
But why do some methods have exclamation marks (
What does it mean?
?) 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
This will output:
In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the
This outputs:
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.
! 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 fooThis will output:
a stringIn 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 barThis outputs:
A STRING
a stringKeep 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 foofoo = "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 barA STRING
a stringContext
Stack Overflow Q#612189, score: 755
Revisions (0)
No revisions yet.