Top Level Namespace

Included Modules

Extended Modules

Defined in:

Constant Summary

ARGF = IO::ARGF.new(ARGV, STDIN)

An IO for reading files from ARGV.

Usage example:

program.cr:

puts ARGF.gets_to_end

A file to read from: (file)

123
$ crystal build program.cr
$ ./program file
123
$ ./program file file
123123
$ # If ARGV is empty, ARGF reads from STDIN instead:
$ echo "hello" | ./program
hello
$ ./program unknown
Unhandled exception: Error opening file with mode 'r': 'unknown': No such file or directory (File::NotFoundError)
...

After a file from ARGV has been read, it's removed from ARGV.

You can manipulate ARGV yourself to control what ARGF operates on. If you remove a file from ARGV, it is ignored by ARGF; if you add files to ARGV, ARGF will read from it.

ARGV.replace ["file1"]
ARGF.gets_to_end # => Content of file1
ARGV             # => []
ARGV << "file2"
ARGF.gets_to_end # => Content of file2
ARGV = Array.new(ARGC_UNSAFE - 1) do |i| String.new(ARGV_UNSAFE[1 + i]) end

An array of arguments passed to the program.

EOL = {% if flag?(:windows) %} "\r\n" {% else %} "\n" {% end %}

The newline constant

PROGRAM_NAME = String.new(ARGV_UNSAFE.value)

The name, the program was called with.

The result may be a relative or absolute path (including symbolic links), just the command name or the empty string.

See Process.executable_path for a more convenient alternative that always returns the absolute real path to the executable file (if it exists).

STDERR = IO::FileDescriptor.from_stdio(2)

The standard error file descriptor.

Typically used to output error messages and diagnostics.

At the start of the program STDERR is configured like this:

  • if it's a TTY device (like the console) then sync is true, meaning that output will be outputted as soon as it is written to STDERR. This is so users can see real time output data.
  • if it's not a TTY device (like a file, or because the output was piped to a file) then sync is false but flush_on_newline is true. This is so that if you pipe the output to a file, and, for example, you tail -f, you can see data on a line-per-line basis. This is convenient but slower than with flush_on_newline set to false. If you need a bit more performance and you don't care about near real-time output you can do STDERR.flush_on_newline = false.

On Unix systems, if the file descriptor is a TTY, the runtime duplicates it. So STDERR.fd might not be 2. The reason for this is to enable non-blocking writes for concurrency. Other fibers can run while waiting on IO. The original file descriptor is inherited from the parent process. Setting it to non-blocking mode would reflect back which can cause problems.

On Windows, STDERR is always blocking.

STDIN = IO::FileDescriptor.from_stdio(0)

The standard input file descriptor. Contains data piped to the program.

On Unix systems, if the file descriptor is a TTY, the runtime duplicates it. So STDIN.fd might not be 0. The reason for this is to enable non-blocking reads for concurrency. Other fibers can run while waiting on user input. The original file descriptor is inherited from the parent process. Setting it to non-blocking mode would reflect back, which can cause problems.

On Windows, STDIN is always blocking.

STDOUT = IO::FileDescriptor.from_stdio(1)

The standard output file descriptor.

Typically used to output data and information.

At the start of the program STDOUT is configured like this:

  • if it's a TTY device (like the console) then sync is true, meaning that output will be outputted as soon as it is written to STDOUT. This is so users can see real time output data.
  • if it's not a TTY device (like a file, or because the output was piped to a file) then sync is false but flush_on_newline is true. This is so that if you pipe the output to a file, and, for example, you tail -f, you can see data on a line-per-line basis. This is convenient but slower than with flush_on_newline set to false. If you need a bit more performance and you don't care about near real-time output you can do STDOUT.flush_on_newline = false.

On Unix systems, if the file descriptor is a TTY, the runtime duplicates it. So STDOUT.fd might not be 1. The reason for this is to enable non-blocking writes for concurrency. Other fibers can run while waiting on IO. The original file descriptor is inherited from the parent process. Setting it to non-blocking mode would reflect back which can cause problems.

On Windows, STDOUT is always blocking.

Method Summary

Macro Summary

Instance methods inherited from module Spec::Methods

after_all(&block) after_all, after_each(&block) after_each, around_all(&block : ExampleGroup::Procsy -> ) around_all, around_each(&block : Example::Procsy -> ) around_each, before_all(&block) before_all, before_each(&block) before_each, context(description = nil, file = __FILE__, line = __LINE__, end_line = __END_LINE__, focus : Bool = false, tags : String | Enumerable(String) | Nil = nil, &block) context, describe(description = nil, file = __FILE__, line = __LINE__, end_line = __END_LINE__, focus : Bool = false, tags : String | Enumerable(String) | Nil = nil, &block) describe, fail(msg, file = __FILE__, line = __LINE__) fail, it(description = "assert", file = __FILE__, line = __LINE__, end_line = __END_LINE__, focus : Bool = false, tags : String | Enumerable(String) | Nil = nil, &block) it, pending(description = "assert", file = __FILE__, line = __LINE__, end_line = __END_LINE__, focus : Bool = false, tags : String | Enumerable(String) | Nil = nil, &)
pending(description = "assert", file = __FILE__, line = __LINE__, end_line = __END_LINE__, focus : Bool = false, tags : String | Enumerable(String) | Nil = nil)
pending
, pending!(msg = "Cannot run example", file = __FILE__, line = __LINE__) pending!

Macros inherited from module Spec::Methods

assert_iterates_iterator(expected, method, *, infinite = false) assert_iterates_iterator, assert_iterates_yielding(expected, method, *, infinite = false, tuple = false) assert_iterates_yielding, assert_prints(call, *, should expectation, file = __FILE__, line = __LINE__)
assert_prints(call, str, *, file = __FILE__, line = __LINE__)
assert_prints
, it_iterates(description, expected, method, *, infinite = false, tuple = false, file = __FILE__, line = __LINE__) it_iterates

Instance methods inherited from module Spec::Expectations

be(value)
be
be
, be_close(expected, delta) be_close, be_empty be_empty, be_false be_false, be_falsey be_falsey, be_nil be_nil, be_true be_true, be_truthy be_truthy, contain(expected) contain, end_with(expected) end_with, eq(value) eq, expect_raises(klass : T.class, message : String | Regex | Nil = nil, file = __FILE__, line = __LINE__, &) forall T expect_raises, match(value) match, start_with(expected) start_with

Macros inherited from module Spec::Expectations

be_a(type) be_a

Method Detail

def `(command) : String #

Returns the standard output of executing command in a subshell. Standard input, and error are inherited. The special $? variable is set to a Process::Status associated with this execution.

It is impossible to call this method with any regular call syntax. There is an associated literal type which calls the method with the literal content as command:

`echo hi`   # => "hi\n"
$?.success? # => true

See Command literals in the language reference.


[View source]
def abort(message = nil, status = 1) : NoReturn #

Terminates execution immediately, printing message to STDERR and then calling exit(status).


[View source]
def at_exit(&handler : Int32, Exception | Nil -> ) : Nil #

Registers the given Proc for execution when the program exits regularly.

A regular exit happens when either

  • the main fiber reaches the end of the program,
  • the main fiber rescues an unhandled exception, or
  • ::exit is called.

Process.exit does not trigger at_exit handlers, nor does external process termination (see Process.on_terminate for handling that).

If multiple handlers are registered, they are executed in reverse order of registration.

def do_at_exit(str1)
  at_exit { print str1 }
end

at_exit { puts "cruel world" }
do_at_exit("goodbye ")
exit

Produces:

goodbye cruel world

The exit status code that will be returned by this program is passed to the block as its first argument. In case of any unhandled exception, it is passed as the second argument to the block, if the program terminates normally or exit(status) is called explicitly, then the second argument will be nil.

NOTE If at_exit is called inside an at_exit handler, it will be called right after the current at_exit handler ends, and then other handlers will be invoked.


[View source]
def caller : Array(String) #

Returns the current execution stack as an array containing strings usually in the form file:line:column or file:line:column in 'method'.


[View source]
def exit(status = 0) : NoReturn #

Terminates execution immediately, returning the given status code to the invoking environment.

Registered at_exit procs are executed.


[View source]
def gets(*args, **options) #

Reads a line from STDIN.

See also: IO#gets.


[View source]
def instance_sizeof(type : Class) : Int32 #

Returns the instance size of the given class as number of bytes.

type must be a constant or typeof() expression. It cannot be evaluated at runtime.

instance_sizeof(String)    # => 16
instance_sizeof(Exception) # => 48

See sizeof for determining the size of value types.

NOTE This is a pseudo-method provided directly by the Crystal compiler. It cannot be redefined nor overridden.


[View source]
def loop(&) #

Repeatedly executes the block.

loop do
  line = gets
  break unless line
  # ...
end

[View source]
def main(argc : Int32, argv : Pointer(Pointer(UInt8))) #

Main function that acts as C's main function. Invokes Crystal.main.

Can be redefined. See Crystal.main for examples.

On Windows the actual entry point is wmain, but there is no need to redefine that. See the file required below for details.


[View source]
def offsetof(type : Class, offset) : Int32 #

Returns the byte offset of an instance variable in a struct or class type.

type must be a constant or typeof() expression. It cannot be evaluated at runtime. offset must be the name of an instance variable of type, prefixed by @, or the index of an element in a Tuple, starting from 0, if type is a Tuple.

offsetof(String, @bytesize)       # => 4
offsetof(Exception, @message)     # => 8
offsetof(Time, @location)         # => 16
offsetof({Int32, Int8, Int32}, 0) # => 0
offsetof({Int32, Int8, Int32}, 1) # => 4
offsetof({Int32, Int8, Int32}, 2) # => 8

NOTE This is a pseudo-method provided directly by the Crystal compiler. It cannot be redefined nor overridden.


[View source]
def p(object) #

Inspects object to STDOUT followed by a newline. Returns object.

See also: Object#inspect(io).


[View source]
def p(*objects) #

Inspects each object in objects to STDOUT, followed by a newline. Returns objects.

See also: Object#inspect(io).


[View source]
def p(**objects) #

Inspects objects to STDOUT, followed by a newline. Returns objects.

p foo: 23, bar: 42 # => {foo: 23, bar: 42}

See Object#inspect(io)


[View source]
def pointerof(variable : T) : Pointer(T) forall T #

Returns a Pointer to the contents of a variable.

variable must be a variable (local, instance, class or library).

a = 1
ptr = pointerof(a)
ptr.value = 2

a # => 2

NOTE This is a pseudo-method provided directly by the Crystal compiler. It cannot be redefined nor overridden.


[View source]
def pp(object) #

Pretty prints object to STDOUT followed by a newline. Returns object.

See also: Object#pretty_print(pp).


[View source]
def pp(*objects) #

Pretty prints each object in objects to STDOUT, followed by a newline. Returns objects.

See also: Object#pretty_print(pp).


[View source]
def pp(**objects) #

Pretty prints objects to STDOUT, followed by a newline. Returns objects.

p foo: 23, bar: 42 # => {foo: 23, bar: 42}

See Object#pretty_print(pp)


[View source]
def print(*objects : _) : Nil #

Prints objects to STDOUT and then invokes STDOUT.flush.

See also: IO#print.


[View source]
def printf(format_string, args : Array | Tuple) : Nil #

Prints a formatted string to STDOUT.

For details on the format string, see sprintf.


[View source]
def printf(format_string, *args) : Nil #

Prints a formatted string to STDOUT.

For details on the format string, see sprintf.


[View source]
def puts(*objects) : Nil #

Prints objects to STDOUT, each followed by a newline character unless the object is a String and already ends with a newline.

See also: IO#puts.


[View source]
def raise(exception : Exception) : NoReturn #

Raises the exception.

This will set the exception's callstack if it hasn't been already. Re-raising a previously caught exception won't replace the callstack.


[View source]
def raise(message : String) : NoReturn #

Raises an Exception with the message.


[View source]
def rand(x) #

See Random#rand(x).


[View source]
def rand : Float64 #

See Random#rand.


[View source]
def read_line(*args, **options) #

Reads a line from STDIN.

See also: IO#read_line.


[View source]
def sizeof(type : Class) : Int32 #

Returns the size of the given type as number of bytes.

type must be a constant or typeof() expression. It cannot be evaluated at runtime.

sizeof(Int32)        # => 4
sizeof(Int64)        # => 8
sizeof(typeof(true)) # => 1

For Reference types, the size is the same as the size of a pointer:

# On a 64 bits machine
sizeof(Pointer(Int32)) # => 8
sizeof(String)         # => 8

This is because a Reference's memory is allocated on the heap and a pointer to it is passed around. The size of a class on the heap can be determined using #instance_sizeof.

NOTE This is a pseudo-method provided directly by the Crystal compiler. It cannot be redefined nor overridden.


[View source]
def sleep(seconds : Number) : Nil #

Blocks the current fiber for the specified number of seconds.

While this fiber is waiting this time, other ready-to-execute fibers might start their execution.

DEPRECATED Use ::sleep(Time::Span) instead


[View source]
def sleep(time : Time::Span) : Nil #

Blocks the current Fiber for the specified time span.

While this fiber is waiting this time, other ready-to-execute fibers might start their execution.


[View source]
def sleep : Nil #

Blocks the current fiber forever.

Meanwhile, other ready-to-execute fibers might start their execution.


[View source]
def spawn(*, name : String | Nil = nil, same_thread = false, &block) #

Spawns a new fiber.

The newly created fiber doesn't run as soon as spawned.

Example:

# Write "1" every 1 second and "2" every 2 seconds for 6 seconds.

ch = Channel(Nil).new

spawn do
  6.times do
    sleep 1.second
    puts 1
  end
  ch.send(nil)
end

spawn do
  3.times do
    sleep 2.seconds
    puts 2
  end
  ch.send(nil)
end

2.times { ch.receive }

[View source]
def sprintf(format_string, args : Array | Tuple) : String #

Returns a formatted string. The string is produced according to the format_string with format specifiers being replaced by values from args formatted according to the specifier.

Within the format string, any characters other than format specifiers (specifiers beginning with %) are copied to the result. The formatter supports the following kinds of format specifiers:

  • Sequential (%.1f). The first % consumes the first argument, the second consumes the second argument, and so on.
  • Positional (%3$.1f). The one-based argument index is specified as part of the flags.
  • Named substitution (%<name>.1f, %{name}). The angle bracket form accepts flags and the curly bracket form doesn't. Exactly one Hash or NamedTuple must be passed as the argument.

Mixing of different kinds of format specifiers is disallowed, except that the two named forms may be used together.

A simple format specifier consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character.

%[flags][width][.precision]type

A formatted substitution is similar but after the percent sign follows the mandatory name of the substitution wrapped in angle brackets.

%<name>[flags][width][.precision]type

The percent sign itself is escaped by %%. No format modifiers are allowed, and no arguments are consumed.

The field type controls how the corresponding argument value is to be interpreted, while the flags modify that interpretation.

The field type characters are:

Field | Integer Format
------+------------------------------------------------------------------
  b   | Formats argument as a binary number.
  d   | Formats argument as a decimal number.
  i   | Same as d.
  o   | Formats argument as an octal number.
  x   | Formats argument as a hexadecimal number using lowercase letters.
  X   | Same as x, but uses uppercase letters.

Field | Float Format
------+---------------------------------------------------------------
  e   | Formats floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to e, but uses an uppercase E to indicate
      | the exponent.
  f   | Formats floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Formats a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to g, but use an uppercase E in exponent form.
  a   | Formats floating point argument as [-]0xh.hhhhp[+-]dd,
      | which consists of an optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to a, but uses uppercase X and P.

Field | Other Format
------+------------------------------------------------------------
  c   | Argument is a single character itself.
  s   | Argument is a string to be substituted. If the format
      | sequence contains a precision, at most that many characters
      | will be copied.

Flags modify the behavior of the format specifiers:

Flag     | Applies to    | Meaning
---------+---------------+----------------------------------------------------
space    | bdiouxX       | Add a leading space character to
         | aAeEfgG       | non-negative numbers. Has no effect if the plus
         | (numeric fmt) | flag is also given.
---------+---------------+----------------------------------------------------
#        | boxX          | Use an alternative format.
         | aAeEfgG       | For x, X, b, prefix any non-zero result with
         |               | 0x, 0X, or 0b respectively.
         |               | For o, prefix any non-zero result with 0o. Note
         |               | that this prefix is different from C and Ruby.
         |               | For a, A, e, E, f, g, G,
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For g and G, do not remove trailing zeros.
---------+---------------+----------------------------------------------------
+        | bdiouxX       | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) |
---------+---------------+----------------------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+----------------------------------------------------
0 (zero) | bdiouxX       | Pad with zeros, not spaces. Has no effect if the
         | aAeEfgG       | number is left-justified, or a precision is given
         | (numeric fmt) | to an integer field type.
---------+---------------+----------------------------------------------------
*        | all           | Use the next argument as the field width or
         |               | precision. If width is negative, set the minus flag
         |               | and use the argument's absolute value as field
         |               | width. If precision is negative, it is ignored.
---------+---------------+----------------------------------------------------
1$ 2$ 3$ | all           | As a flag, specifies the one-based argument index
...      |               | for a positional format specifier.
         |               | Immediately after *, use the argument at the given
         |               | one-based index as the width or precision, instead
         |               | of the next argument. The entire format string must
         |               | also use positional format specifiers throughout.

Examples of flags:

Decimal number conversion:

sprintf "%d", 123  # => "123"
sprintf "%+d", 123 # => "+123"
sprintf "% d", 123 # => " 123"

Octal number conversion:

sprintf "%o", 123   # => "173"
sprintf "%+o", 123  # => "+173"
sprintf "%o", -123  # => "-173"
sprintf "%+o", -123 # => "-173"

Hexadecimal number conversion:

sprintf "%x", 123   # => "7b"
sprintf "%+x", 123  # => "+7b"
sprintf "%x", -123  # => "-7b"
sprintf "%+x", -123 # => "-7b"
sprintf "%#x", 0    # => "0"
sprintf "% x", 123  # => " 7b"
sprintf "% x", -123 # => "-7b"
sprintf "%X", 123   # => "7B"
sprintf "%#X", -123 # => "-0X7B"

Binary number conversion:

sprintf "%b", 123    # => "1111011"
sprintf "%+b", 123   # => "+1111011"
sprintf "%+b", -123  # => "-1111011"
sprintf "%b", -123   # => "-1111011"
sprintf "%#b", 0     # => "0"
sprintf "% b", 123   # => " 1111011"
sprintf "%+ b", 123  # => "+1111011"
sprintf "% b", -123  # => "-1111011"
sprintf "%+ b", -123 # => "-1111011"
sprintf "%#b", 123   # => "0b1111011"

Floating point conversion:

sprintf "%a", 123 # => "0x1.ecp+6"
sprintf "%A", 123 # => "0X1.ECP+6"

Exponential form conversion:

sprintf "%g", 123.4          # => "123.4"
sprintf "%g", 123.4567       # => "123.457"
sprintf "%20.8g", 1234.56789 # => "           1234.5679"
sprintf "%20.8g", 123456789  # => "       1.2345679e+08"
sprintf "%20.8G", 123456789  # => "       1.2345679E+08"
sprintf "%20.8g", -123456789 # => "      -1.2345679e+08"
sprintf "%20.8G", -123456789 # => "      -1.2345679E+08"

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

sprintf "%20d", 123   # => "                 123"
sprintf "%+20d", 123  # => "                +123"
sprintf "%020d", 123  # => "00000000000000000123"
sprintf "%+020d", 123 # => "+0000000000000000123"
sprintf "% 020d", 123 # => " 0000000000000000123"
sprintf "%-20d", 123  # => "123                 "
sprintf "%-+20d", 123 # => "+123                "
sprintf "%- 20d", 123 # => " 123                "
sprintf "%020x", -123 # => "-000000000000000007b"
sprintf "%020X", -123 # => "-000000000000000007B"

For numeric fields, the precision controls the number of decimal places displayed.

For string fields, the precision determines the maximum number of characters to be copied from the string.

Examples of precisions:

Precision for d, o, x and b is minimum number of digits:

sprintf "%20.8d", 123   # => "            00000123"
sprintf "%020.8d", 123  # => "            00000123"
sprintf "%20.8o", 123   # => "            00000173"
sprintf "%020.8o", 123  # => "            00000173"
sprintf "%20.8x", 123   # => "            0000007b"
sprintf "%020.8x", 123  # => "            0000007b"
sprintf "%20.8b", 123   # => "            01111011"
sprintf "%20.8d", -123  # => "           -00000123"
sprintf "%020.8d", -123 # => "           -00000123"
sprintf "%20.8o", -123  # => "           -00000173"
sprintf "%20.8x", -123  # => "           -0000007b"
sprintf "%20.8b", -11   # => "           -00001011"

Precision for e is number of digits after the decimal point:

sprintf "%20.8e", 1234.56789 # => "      1.23456789e+03"

Precision for f is number of digits after the decimal point:

sprintf "%20.8f", 1234.56789 # => "       1234.56789000"

Precision for g is number of significant digits:

sprintf "%20.8g", 1234.56789 # => "           1234.5679"
sprintf "%20.8g", 123456789  # => "       1.2345679e+08"
sprintf "%-20.8g", 123456789 # => "1.2345679e+08       "

Precision for s is maximum number of characters:

sprintf "%20.8s", "string test" # => "            string t"

Additional examples:

sprintf "%d %04x", 123, 123                 # => "123 007b"
sprintf "%08b '%4s'", 123, 123              # => "01111011 ' 123'"
sprintf "%+g:% g:%-g", 1.23, 1.23, 1.23     # => "+1.23: 1.23:1.23"
sprintf "%-3$*1$.*2$s", 10, 5, "abcdefghij" # => "abcde     "

[View source]
def sprintf(format_string, *args) : String #

Returns a formatted string. The string is produced according to the format_string with format specifiers being replaced by values from args formatted according to the specifier.

Within the format string, any characters other than format specifiers (specifiers beginning with %) are copied to the result. The formatter supports the following kinds of format specifiers:

  • Sequential (%.1f). The first % consumes the first argument, the second consumes the second argument, and so on.
  • Positional (%3$.1f). The one-based argument index is specified as part of the flags.
  • Named substitution (%<name>.1f, %{name}). The angle bracket form accepts flags and the curly bracket form doesn't. Exactly one Hash or NamedTuple must be passed as the argument.

Mixing of different kinds of format specifiers is disallowed, except that the two named forms may be used together.

A simple format specifier consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character.

%[flags][width][.precision]type

A formatted substitution is similar but after the percent sign follows the mandatory name of the substitution wrapped in angle brackets.

%<name>[flags][width][.precision]type

The percent sign itself is escaped by %%. No format modifiers are allowed, and no arguments are consumed.

The field type controls how the corresponding argument value is to be interpreted, while the flags modify that interpretation.

The field type characters are:

Field | Integer Format
------+------------------------------------------------------------------
  b   | Formats argument as a binary number.
  d   | Formats argument as a decimal number.
  i   | Same as d.
  o   | Formats argument as an octal number.
  x   | Formats argument as a hexadecimal number using lowercase letters.
  X   | Same as x, but uses uppercase letters.

Field | Float Format
------+---------------------------------------------------------------
  e   | Formats floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to e, but uses an uppercase E to indicate
      | the exponent.
  f   | Formats floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Formats a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to g, but use an uppercase E in exponent form.
  a   | Formats floating point argument as [-]0xh.hhhhp[+-]dd,
      | which consists of an optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to a, but uses uppercase X and P.

Field | Other Format
------+------------------------------------------------------------
  c   | Argument is a single character itself.
  s   | Argument is a string to be substituted. If the format
      | sequence contains a precision, at most that many characters
      | will be copied.

Flags modify the behavior of the format specifiers:

Flag     | Applies to    | Meaning
---------+---------------+----------------------------------------------------
space    | bdiouxX       | Add a leading space character to
         | aAeEfgG       | non-negative numbers. Has no effect if the plus
         | (numeric fmt) | flag is also given.
---------+---------------+----------------------------------------------------
#        | boxX          | Use an alternative format.
         | aAeEfgG       | For x, X, b, prefix any non-zero result with
         |               | 0x, 0X, or 0b respectively.
         |               | For o, prefix any non-zero result with 0o. Note
         |               | that this prefix is different from C and Ruby.
         |               | For a, A, e, E, f, g, G,
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For g and G, do not remove trailing zeros.
---------+---------------+----------------------------------------------------
+        | bdiouxX       | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) |
---------+---------------+----------------------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+----------------------------------------------------
0 (zero) | bdiouxX       | Pad with zeros, not spaces. Has no effect if the
         | aAeEfgG       | number is left-justified, or a precision is given
         | (numeric fmt) | to an integer field type.
---------+---------------+----------------------------------------------------
*        | all           | Use the next argument as the field width or
         |               | precision. If width is negative, set the minus flag
         |               | and use the argument's absolute value as field
         |               | width. If precision is negative, it is ignored.
---------+---------------+----------------------------------------------------
1$ 2$ 3$ | all           | As a flag, specifies the one-based argument index
...      |               | for a positional format specifier.
         |               | Immediately after *, use the argument at the given
         |               | one-based index as the width or precision, instead
         |               | of the next argument. The entire format string must
         |               | also use positional format specifiers throughout.

Examples of flags:

Decimal number conversion:

sprintf "%d", 123  # => "123"
sprintf "%+d", 123 # => "+123"
sprintf "% d", 123 # => " 123"

Octal number conversion:

sprintf "%o", 123   # => "173"
sprintf "%+o", 123  # => "+173"
sprintf "%o", -123  # => "-173"
sprintf "%+o", -123 # => "-173"

Hexadecimal number conversion:

sprintf "%x", 123   # => "7b"
sprintf "%+x", 123  # => "+7b"
sprintf "%x", -123  # => "-7b"
sprintf "%+x", -123 # => "-7b"
sprintf "%#x", 0    # => "0"
sprintf "% x", 123  # => " 7b"
sprintf "% x", -123 # => "-7b"
sprintf "%X", 123   # => "7B"
sprintf "%#X", -123 # => "-0X7B"

Binary number conversion:

sprintf "%b", 123    # => "1111011"
sprintf "%+b", 123   # => "+1111011"
sprintf "%+b", -123  # => "-1111011"
sprintf "%b", -123   # => "-1111011"
sprintf "%#b", 0     # => "0"
sprintf "% b", 123   # => " 1111011"
sprintf "%+ b", 123  # => "+1111011"
sprintf "% b", -123  # => "-1111011"
sprintf "%+ b", -123 # => "-1111011"
sprintf "%#b", 123   # => "0b1111011"

Floating point conversion:

sprintf "%a", 123 # => "0x1.ecp+6"
sprintf "%A", 123 # => "0X1.ECP+6"

Exponential form conversion:

sprintf "%g", 123.4          # => "123.4"
sprintf "%g", 123.4567       # => "123.457"
sprintf "%20.8g", 1234.56789 # => "           1234.5679"
sprintf "%20.8g", 123456789  # => "       1.2345679e+08"
sprintf "%20.8G", 123456789  # => "       1.2345679E+08"
sprintf "%20.8g", -123456789 # => "      -1.2345679e+08"
sprintf "%20.8G", -123456789 # => "      -1.2345679E+08"

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

sprintf "%20d", 123   # => "                 123"
sprintf "%+20d", 123  # => "                +123"
sprintf "%020d", 123  # => "00000000000000000123"
sprintf "%+020d", 123 # => "+0000000000000000123"
sprintf "% 020d", 123 # => " 0000000000000000123"
sprintf "%-20d", 123  # => "123                 "
sprintf "%-+20d", 123 # => "+123                "
sprintf "%- 20d", 123 # => " 123                "
sprintf "%020x", -123 # => "-000000000000000007b"
sprintf "%020X", -123 # => "-000000000000000007B"

For numeric fields, the precision controls the number of decimal places displayed.

For string fields, the precision determines the maximum number of characters to be copied from the string.

Examples of precisions:

Precision for d, o, x and b is minimum number of digits:

sprintf "%20.8d", 123   # => "            00000123"
sprintf "%020.8d", 123  # => "            00000123"
sprintf "%20.8o", 123   # => "            00000173"
sprintf "%020.8o", 123  # => "            00000173"
sprintf "%20.8x", 123   # => "            0000007b"
sprintf "%020.8x", 123  # => "            0000007b"
sprintf "%20.8b", 123   # => "            01111011"
sprintf "%20.8d", -123  # => "           -00000123"
sprintf "%020.8d", -123 # => "           -00000123"
sprintf "%20.8o", -123  # => "           -00000173"
sprintf "%20.8x", -123  # => "           -0000007b"
sprintf "%20.8b", -11   # => "           -00001011"

Precision for e is number of digits after the decimal point:

sprintf "%20.8e", 1234.56789 # => "      1.23456789e+03"

Precision for f is number of digits after the decimal point:

sprintf "%20.8f", 1234.56789 # => "       1234.56789000"

Precision for g is number of significant digits:

sprintf "%20.8g", 1234.56789 # => "           1234.5679"
sprintf "%20.8g", 123456789  # => "       1.2345679e+08"
sprintf "%-20.8g", 123456789 # => "1.2345679e+08       "

Precision for s is maximum number of characters:

sprintf "%20.8s", "string test" # => "            string t"

Additional examples:

sprintf "%d %04x", 123, 123                 # => "123 007b"
sprintf "%08b '%4s'", 123, 123              # => "01111011 ' 123'"
sprintf "%+g:% g:%-g", 1.23, 1.23, 1.23     # => "+1.23: 1.23:1.23"
sprintf "%-3$*1$.*2$s", 10, 5, "abcdefghij" # => "abcde     "

[View source]
def system(command : String, args = nil) : Bool #

Executes the given command in a subshell. Standard input, output and error are inherited. Returns true if the command gives zero exit code, false otherwise. The special $? variable is set to a Process::Status associated with this execution.

If command contains no spaces and args is given, it will become its argument list.

If command contains spaces and args is given, command must include "${@}" (including the quotes) to receive the argument list.

No shell interpretation is done in args.

Example:

system("echo *")

Produces:

LICENSE shard.yml Readme.md spec src

[View source]
def timeout_select_action(timeout : Time::Span) : Channel::TimeoutAction #

Timeout keyword for use in select.

select
when x = ch.receive
  puts "got #{x}"
when timeout(1.seconds)
  puts "timeout"
end

NOTE It won't trigger if the select has an else case (i.e.: a non-blocking select).


[View source]
def typeof(*expression) : Class #

Returns the type of an expression.

typeof(1) # => Int32

It accepts multiple arguments, and the result is the union of the expression types:

typeof(1, "a", 'a') # => (Int32 | String | Char)

The expressions passed as arguments to typeof do not evaluate. The compiler only analyzes their return type.

NOTE This is a pseudo-method provided directly by the Crystal compiler. It cannot be redefined nor overridden.


[View source]

Macro Detail

macro debugger #

[View source]
macro p!(*exps) #

Prints a series of expressions together with their inspected values. Useful for print style debugging.

a = 1
p! a # => "a # => 1"

p! [1, 2, 3].map(&.to_s) # => "[1, 2, 3].map(&.to_s) # => ["1", "2", "3"]"

See also: p, Object#inspect.


[View source]
macro pp!(*exps) #

Prints a series of expressions together with their pretty printed values. Useful for print style debugging.

a = 1
pp! a # => "a # => 1"

pp! [1, 2, 3].map(&.to_s) # => "[1, 2, 3].map(&.to_s) # => ["1", "2", "3"]"

See also: pp, Object#pretty_inspect.


[View source]
macro record(__name name, *properties, **kwargs) #

Defines a Struct type called name with the given properties.

The generated struct has a constructor with the given properties in the same order as declared. The struct only provides getters, not setters, making it immutable by default.

record Point, x : Int32, y : Int32

p = Point.new 1, 2 # => #<Point(@x=1, @y=2)>
p.x                # => 1
p.y                # => 2

The properties are a sequence of type declarations (x : Int32, x : Int32 = 0) or assigns (x = 0). They declare instance variables and respective getter methods of their name with optional type restrictions and default value.

When passing a block to this macro its body is inserted inside the struct definition. This allows to define additional methods or include modules into the record type (reopening the type would work as well).

record Person, first_name : String, last_name : String do
  def full_name
    "#{first_name} #{last_name}"
  end
end

person = Person.new "John", "Doe"
person.full_name # => "John Doe"

An example with type declarations and default values:

record Point, x : Int32 = 0, y : Int32 = 0

Point.new      # => #<Point(@x=0, @y=0)>
Point.new y: 2 # => #<Point(@x=0, @y=2)>

An example with assignments (in this case the compiler must be able to infer the types from the default values):

record Point, x = 0, y = 0

Point.new      # => #<Point(@x=0, @y=0)>
Point.new y: 2 # => #<Point(@x=0, @y=2)>

This macro also provides a #copy_with method which returns a copy of the record with the provided properties altered.

record Point, x = 0, y = 0

p = Point.new y: 2 # => #<Point(@x=0, @y=2)>
p.copy_with x: 3   # => #<Point(@x=3, @y=2)>
p                  # => #<Point(@x=0, @y=2)>

[View source]
macro spawn(call, *, name = nil, same_thread = false, &block) #

Spawns a fiber by first creating a Proc, passing the call's expressions to it, and letting the Proc finally invoke the call.

Compare this:

i = 0
while i < 5
  spawn { print(i) }
  i += 1
end
Fiber.yield
# Output: 55555

To this:

i = 0
while i < 5
  spawn print(i)
  i += 1
end
Fiber.yield
# Output: 01234

This is because in the first case all spawned fibers refer to the same local variable, while in the second example copies of i are passed to a Proc that eventually invokes the call.


[View source]