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?".
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
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.
BASIC: What does an exclamation mark at the end of a function name mean?
It means the function returns a SINGLE
. Exclamation point is a shortcut for As Single
.
what does ? ? mean in ruby
Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.
When you write a function that can only return true or false, you should end the function name with a question mark.
The example you gave shows a ternary statement, which is a one-line if-statement. .nil?
is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil?
function returns true, it gets nil as value, else it gets the File.join(root_dir, '/')
as value.
It can be rewritten like so:
if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end
What does the exclamation mark mean before a function call?
"!"
is a new dart operator for conversion from a nullable to a non-nullable type.
Read here and here about sound null safety.
Use it only if you are absolutely sure that the value will never be null and do not confuse it with the conditional property access operator.
What does an exclamation mark mean after the name of a function?
In Julia, it's a convention to append !
to names of functions that modify their arguments. The reason is Julia function arguments are passed-by-sharing, without this "bang" convention, it's not easy to know whether a function will change the content of input arguments or not.
What does the exclamation mark do before the function?
JavaScript syntax 101: here is a function declaration:
function foo() {}
Note that there’s no semicolon; this is just a function declaration. You would need an invocation, foo()
, to actually run the function.
Now, when we add the seemingly innocuous exclamation mark: !function foo() {}
it turns it into an expression. It is now a function expression.
The !
alone doesn’t invoke the function, of course, but we can now put ()
at the end: !function foo() {}()
, which has higher precedence than !
and instantly calls the function.
function foo() {}()
would be a syntax error because you can’t put arguments (()
) right after a function declaration.
So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:
(function(){})();
Lastly, !
makes the expression return a boolean based on the return value of the function. Usually, an immediately invoked function expression (IIFE) doesn’t explicitly return anything, so its return value will be undefined
, which leaves us with !undefined
which is true
. This boolean isn’t used.
What does an exclamation mark before a variable mean in JavaScript
!
is the logical not operator in JavaScript.
Formally
!expression
is read as:
- Take
expression
and evaluate it. In your case that'svariable.onsubmit
- Case the result of that evaluation and convert it to a boolean. In your case since
onsubmit
is likely a function, it means - if the function is null or undefined - return false, otherwise return true. - If that evaluation is true, return false. Otherwise return true.
In your case
In your case !variable.onsubmit
means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
Simply put - !variable
means take the truth value of variable
and negate it.
Thus, if (!variable) {
will enter the if
clause if variable is false
(or coerces to false)
In total
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - check if variable.onsubmit
is defined and truthy (thus true), then it checks if calling onsubmit
returns a result that coerces to true. In a short line it checks if there is no onsubmit
or it returns true.
Next time, how do I find this myself?
- MDN has a list of operators here.
- The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.
Why does the println! function use an exclamation mark in Rust?
println!
is not a function, it is a macro. Macros use !
to distinguish them from normal method calls. The documentation contains more information.
See also:
- What is the difference between macros and functions in Rust?
Rust uses the Option
type to denote optional data. It has an unwrap
method.
Rust 1.13 added the question mark operator ?
as an analog of the try!
macro (originally proposed via RFC 243).
An excellent explanation of the question mark operator is in The Rust Programming Language.
fn foo() -> Result<i32, Error> {
Ok(4)
}
fn bar() -> Result<i32, Error> {
let a = foo()?;
Ok(a + 4)
}
The question mark operator also extends to Option
, so you may see it used to unwrap a value or return None
from the function. This is different from just unwrapping as the program will not panic:
fn foo() -> Option<i32> {
None
}
fn bar() -> Option<i32> {
let a = foo()?;
Some(a + 4)
}
Related Topics
Ruby/Rails - Change the Timezone of a Time, Without Changing the Value
Undefined Method 'Visit' When Using Rspec and Capybara in Rails
Difference Between $Stdout and Stdout in Ruby
How to Implement a Short Url Like the Urls in Twitter
Execute Bash Commands from a Rakefile
Unzip (Zip, Tar, Tag.Gz) Files With Ruby
In Rails, How to Add a New Method to String Class
Ruby 1.9.2 How to Install Rmagick on Windows
Include Jekyll/Liquid Template Data in a Yaml Variable
What Is the "Right" Way to Iterate Through an Array in Ruby
Ruby: How to Turn a Hash into Http Parameters
Converting an Integer to a Hexadecimal String in Ruby
Rails - Best-Practice: How to Create Dependent Has_One Relations