The Crystal Programming Language Forum

« ! », « ? » And « & » in Crystal What do they mean

Hi,

I’m familiar with some of the use of the « ! », « ? » And « & » operators in C, C++ etc…

However, in addition to their use of in C, these operators seem to have special meanings in Crystal, for instance:

  • Hello()
  • Hello?() (or hello?())
  • Hello!() (or hello()!)

Seem to mean different things in Crystal

I have also seen « & » when methods acting on iterables are chained, something like:

MyIter.filter.&.map(my-func())

What is the use of « & » in this context?

? in crystal has a few meanings depending on context:

  1. Representing a type union with Nil. E.g. String? which is equivalent to String | Nil.
  2. A method that would return nil. E.g. [1, 2, 3][5]? # => nil
  3. A method that returns a boolean. E.g. user.active?.

! on the other hand is usually used to denote a method call that either modifies self, or would raise an exception.

& is used mainly regarding blocks. See Blocks and Procs - Crystal.

2 Likes

Just to clarify: a question mark or a bang at the end of a method name is just part of the name. It’s like any other name. Then there are conventions about when to use these suffixes and what they mean.

2 Likes

Tank you.