what does "?" in ruby means? - ruby

I want to know it real meaning of it and how to use it exactly.
Another question is about assert I saw
assert product.valid? product.errors.full_messages
and
assert product.valid?
But I can't find syntax for those assert what does second arg for assert (product.errors.full_messages) means or it is arg for ?
Thanks

Ruby uses specific naming conventions for methods. It allows you to quickly identify the side effects they may have, or the return type..
These conventions use special markers such as "!" and "?" at the end of method names. This is uncommon since most programming languages tend to forbid such characters in identifiers, but nevertheless, it is truly part of the method name. (and should not be confused with operators)
Post fixing "?" means that the method returns a boolean. It's a convenient way to replace the "is" prefix. (this convention tends to exist in lisp dialects too)
Post fixing "!" means that the method will modify the instance, and thus won't act on/return a copy.
Note that these are just conventions. In no way you have to follow it, but it is considered a good practice.

It is purely a convention, it has no formal meaning. It isn't unusual for people to get confused by this, since many (most?) languages don't allow characters such as ? and ! in identifiers.

It's just convention to put it on a method that returns a boolean afaik. Rather than making everythign IsSomething.

Related

Why does the Rubocop default guidelines recommend parentheses in method definitions?

Why does Rubocop / the community-driven Ruby style guide recommend parentheses in method definitions?
def my_method(param1, param2)
end
# instead of
def my_method param1, param2
end
Method calls are allowed with or without parentheses depending on the situation. However, my first impression is that lack of parentheses in method calls are much more potentially ambiguous than lack of parentheses in method definitions. Was there a reason behind it, e.g. to make code more fool-proof, or did it happen because of "historical reasons" or "because it was the most widespread style"?
Clarification:
I am not asking for opinions about which style is easier to read.
The lint Lint/AmbiguousOperator is based on the idea that do_something *some_array is ambiguous and a source for bugs (Link). I wondered if this is the same case for Style/MethodDefParentheses (Link).
After going back to find the actual names of those Cops, my best guess right now is that there is no "technical" reason, but rather one is a proper "lint" and the other a "style" matter.
The rationale is omitted in the initial commit, of which this rule was part, indicating that there was no particular technical reason for it.
The fact that the corresponding cop is placed in the Style department, rather than Lint, serves as further proof that this is a matter of just that, style.
Method definitions have a very simple syntax. The def keyword is (optionally) followed by arguments, which must be followed by a terminator (newline or ;).
The possible variations are:
single line method definitions,
inline modifiers, e.g. private,
default- and keyword arguments,
splat- and block arguments.
All of these work fine both with and without parentheses. Furthermore, running a file with an unparenthesized method definition using the -w flag raises no warnings.
These factors together rule out the possibility that the parentheses are recommended to avoid ambiguity.

What is the convention for considering a function with side-effects in Racket/Scheme?

Obviously, it is a convention in Racket/Scheme to append an exclamation point to function names that perform mutation. For example, in Racket, set!, box-set!, vector-set!, etc. Certain functions have side-effects, like print, but since those side-effects are "harmless," I understand why they don't usually come with exclamation marks attached.
However, this convention is arbitrarily violated. For example, async-channel-get and async-channel-put clearly perform mutation, but they don't have the "mutation marker" appended to their names. This can be somewhat justified by pointing out that these are channels, clearly mutation-based, so the "!" would be superfluous.
This is not a valid justification for everything, though. Racket's WebSockets library provides ws-send! and ws-close! functions, both with the obvious markers, but ws-recv does not! Is this just an isolated violation of the convention, or is there some rule?
I ask this mostly to be sure of how I should name functions in my own code. When should I use the exclamation mark, when should I not? I recognize that it's just a convention, not a rule, and it will likely be somewhat inconsistent, but I still would like to know what the best practices are.
I don't think #!racket has its own naming convention, but according to this R5RS page you can read:
The names of procedures and syntactic forms that cause side effects
end with an exclamation point ( ! ). These include set! and
vector-set!. Procedures that perform input or output technically cause
side effects, but their names are exceptions to this rule.
In the Scheme wiki variable naming convention it says procedure! is for "significant side effects". IMO that means the side effects is the hero of the procedure as in set-car! and set! while read returns a value which perhaps is the main feature of read?

What is special about boolean?

In Ruby, there is a convention to have a method name end with a question mark to indicate that its return value is boolean. Why is boolean considered so special? Is there anything convenient if you know that a method's return value is particularly boolean? After all, in Ruby, you can insert all kinds of value returning (getter) methods into a conditional without caring whether it is boolean or not.
I think it is a waste to use the question mark just for indicating a boolean value. There should be more useful uses. I have plenty of use case where I want to have a pair of getter and setter methods, where the setter method should return self so that I can use it in a method chain. And naming them something like get_foo and set_foo looks cumbersome. Rather than following the convention, I am tempted to name a pair of getter and setter methods like this:
def foo?; #foo end
def foo v; #foo = v end
where the value of #foo is not (necessarily) boolean. (Besides potential criticism that breaking the convention will confuse other programmers), is there something wrong with doing that?
There is nothing special at all, it's just a convention. A question can be answered with "yes" or "no", but also with another stuff like someone's name.
By returning a boolean on methods with a question mark, it indicates it to be an explicit behavior.
If you make the answer be "yes" or "no", it's easy for the reader of your code to identify the behavior of your method without even looking at the implementation. On the other hand, if you make it return any other type, it is more difficult for the reader to understand your code without reading your class and method definition.
With a boolean there are only two possible answers. If the return value is not boolean it can be anything, which would not help at all. You would still need to look at the method implementation. You should always look further to understand some piece of code, but using this convention makes it simpler.
There is a convention to use question mark in method names to indicate that a method is a predicate. AFAIK, this predicate is not required (by the convention) to return a boolean value, thanks to simple rules for truthy/falsey values.
Besides potential criticism that breaking the convention will confuse other programmers, is there something wrong with doing that?
Confusing and surprising fellow programmers is bad. Ruby couldn't care less. It's just a convention. And conventions exist for a reason.
You can put anything in a flow control construct, but semantically booleans are appropriate. "If" in real human language typically takes a boolean, and the same is true of the construct in many programming languages. Ruby likes to make things convenient and assigns a "truthiness" value to everything in the language, which affects how it behaves in a boolean context.
In other words, booleans are the only things that are almost exclusively used for flow control, so the convention is to make them look "right" for flow-control constructs. It's their native environment.
(Besides potential criticism that breaking the convention will confuse other programmers), is there something wrong with doing that?
In the same sense that there is nothing wrong with naming all your variables after 1920s comedians, no, there's nothing wrong with that. But also in the same sense as naming all your variables after 1920s comedians, it isn't a very good idea. Nowhere in any language that I know of -- human or computer -- does the question mark mean "get." So the semantics of your code are off with that convention.
This question and the answers boil down to "POLS" AKA "Principle of Least Surprise".
A method name can be a random choice of letters and numbers separated by underscores, with '!', '?' and '=' sprinkled through them, if we chose to do so. They could be randomly created by the code at run time, and, as long as the rest of the code used the same arrangement of characters, the program would run and Ruby would be happy.
We humans, the programmers, determine the name of the methods used, to represent something, a characteristic or an action. Trying to use randomly named methods would lead to madness, or at least a very hard to maintain program. So, instead, we try to use sensible names for things. Sometimes they're verbs or adjectives, sometimes they're more descriptive because the method does several things.
As part of that naming, sometimes we want to provide additional hints about the behavior of the method. By convention in Ruby, we use "!" to warn the coder that the method changes something or is destructive. "=" indicates the method takes a parameter and assigns it to the receiver/object. It's a setter method and in many other languages it'd be idiomatic to use "set_flag..." or "set_value..." as the name. It's just a convention in that language, and followed by developers in the language.
We use "?" in Ruby to ask a question about an object, whether it is, or isn't, true about that object. We could say "is_true?" or "true?" and indicate we are testing whether something is true about it. If it's true, or false, it's a Boolean response so we return a true/false value.

Naming convention for syntactic sugar methods

I'm build a library for generic reporting, Excel(using Spreadsheet), and most of the time I'll be writing things out on the last created worksheet (or active as I mostly refer to it).
So I'm wondering if there's a naming convention for methods that are mostly sugar to the normal/unsugared method.
For instance I saw a blog post, scroll down to Composite, a while ago where the author used the #method for the sugared, and #method! when unsugared/manual.
Could this be said to be a normal way of doing things, or just an odd implementation?
What I'm thinking of doing now is:
add_row(data)
add_row!(sheet, data)
This feels like a good fit to me, but is there a consensus on how these kinds of methods should be named?
Edit
I'm aware that the ! is used for "dangerous" methods and ? for query/boolean responses. Which is why I got curious whether the usage in Prawn (the blog post) could be said to be normal.
I think it's fair to say that your definitions:
add_row(data)
add_row!(sheet, data)
are going to confuse Ruby users. There is a good number of naming conventions is the Ruby community that are considered like a de-facto standard for naming. For example, the bang methods are meant to modify the receiver, see map and map!. Another convention is add the ? as a suffix to methods that returns a boolean. See all? or any? for a reference.
I used to see bang-methods as more dangerous version of a regular named method:
Array#reverse! that modifies array itself instead of returning new array with reversed order of elements.
ActiveRecord::Base#save! (from Rails) validates model and save it if it's valid. But unlike regular version that return true or false depending on whether the model was saved or not raises an exception if model is invalid.
I don't remember seeing bang-methods as sugared alternatives for regular methods. May be I'd give such methods their own distinct name other then just adding a bang to regular version name.
Why have two separate methods? You could for example make the sheet an optional parameter, for example
def add_row(sheet = active_sheet, data)
...
end
default values don't have to just be static values - in this case it's calling the active_sheet method. If my memory is correct prior to ruby 1.9 you'd have to swap the parameters as optional parameters couldn't be followed by non optional ones.
I'd agree with other answers that ! has rather different connotations to me.

Guide to Win32 API Data Type Naming Conventions

I'm new to programming with the Win32 API, and I'm still getting used to the prefix / suffix data type naming conventions. While Google and a little common sense will normally explain what the prefix is referring to, it would be nice if there was one (relatively) concise guide to explain them. Does anyone know of a resource like this?
And on a related note, what does the '_' (underscore) prefix mean with a variable? Does that underscore have a name, other than "underscore"?
The naming convention is called Hungarian Notation, as mentioned by others. Since you're not familiar with it, and are probably going to start using it, it is worth mentioning there are two main flavors of Hungarian:
prefix the variable with its type code
prefix the variable with its usage code
The difference is visible when, for instance, an int is used to describe the number of bytes in a certain strings. On the former, nLen will be used, meaning the variable is an int. On the later, cbLen will be used, meaning the variable counts bytes (as opposed to cchLen, which counts characters). Give this article a look, should give you a better explanation.
As for the underscores in front of a variable or function - this is a naming convention reserved for the compiler and its standard library. Some people use it for other purposes, but they really shouldn't. The purpose of the convention is to provide the compiler a naming standard that will prevent collisions with names given by the user.
Win32 API follows Hungarian Notation
It's called a hungarian notation, Wikipedia has some information about it, and there's something on MSDN.

Resources