Why are exclamation marks used in Ruby methods?
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.
what is the use of ! sign in some ruby methods
As a convention, identifier? are used as predicate names, and identifier! are used for the more destructive (or more dangerous) methods than the method which have same name without !.
Source
Example:
lstrip
will return a new string with leading spaces removed thus original string is un-modified.lstrip!
will modify the string-in place
What is the purpose of ! and ? at the end of method names?
It's "just sugarcoating" for readability, but they do have common meanings:
- Methods ending in
!
perform some permanent or potentially dangerous change; for example:Enumerable#sort
returns a sorted version of the object whileEnumerable#sort!
sorts it in place.- In Rails,
ActiveRecord::Base#save
returns false if saving failed, whileActiveRecord::Base#save!
raises an exception. Kernel::exit
causes a script to exit, whileKernel::exit!
does so immediately, bypassing any exit handlers.
- Methods ending in
?
return a boolean, which makes the code flow even more intuitively like a sentence —if number.zero?
reads like "if the number is zero", butif number.zero
just looks weird.
In your example, name.reverse
evaluates to a reversed string, but only after the name.reverse!
line does the name
variable actually contain the reversed name. name.is_binary_data?
looks like "is name
binary data?".
Exclamation points before a variable in Ruby
!
is a just a not operator.
b.nil?
is a method that checks the value for b is nil or not. Returns a boolean.
!b.nil? ? a + b : a
is a ternary operation is action. It works like this :
if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this
which is equivalent of saying
if a then b else c end
So relating with above statement if !b.nil?
is true
answer is a+b
else it is a
.
Read more here
What is the purpose of exclamation marks in field definitions for GraphQL types in Ruby?
It's a mandatory (non-nullable) field. Implementation of:
String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. In the type language, we'll represent those with an exclamation mark.
https://graphql.org/learn/schema/#object-types-and-fields
It seems it was replaced by keyword syntax:
field :handle, String, null: false
http://graphql-ruby.org/type_definitions/objects.html
Where to put exclamation mark when methods are chained
Exclamation marks are not modifiers.
array.reject!(&:blank?).map!(&:to_i).reject!{|i| i == 0}
However, this code is subtly wrong. From reject!
docs:
returns nil if no changes were made.
Whoops! This could break your whole chain. Instead, you're supposed to use delete_if, which always returns the array.
array.delete_if(&:blank?).map!(&:to_i).delete_if{|i| i == 0}
Yes, it's confusing it doesn't have a bang, but it does modify in-place. From the docs:
The array is changed instantly every time the block is called, not after the iteration is over.
What does the question mark at the end of a method name mean in Ruby?
It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value).
The question mark is a valid character at the end of a method name.
https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names
Related Topics
Error: While Executing Gem ... (Gem::Filepermissionerror)
Ruby, Difference Between Exec, System and %X() or Backticks
How to Get a Random Number in Ruby
Why Doesn't Ruby Support Method Overloading
When to Use Symbols Instead of Strings in Ruby
An How to Support Tags in a Jekyll Blog
What's Different Between Each and Collect Method in Ruby
Ruby 2.4 and Rails 4 Stack Level Too Deep (Systemstackerror)
How to Test For (Activerecord) Object Equality
Validation for Non-Negative Integers and Decimal Values
Rvm Installation Not Working: "Rvm Is Not a Function"
No Such File to Load - Rubygems (Loaderror)
How to Split (Chunk) a Ruby Array into Parts of X Elements
Rhc Setup Gives Error 'No Such File Dl/Import'