Top Level Namespace

Included Modules

Extended Modules

Defined in:

Constant Summary

ARGF = IO::ARGF.new(ARGV, STDIN)
ARGV = Array.new(ARGC_UNSAFE - 1) do |i| String.new(ARGV_UNSAFE[1 + i]) end
PROGRAM_NAME = String.new(ARGV_UNSAFE.value)
STDERR = (IO::FileDescriptor.new(2, blocking: (LibC.isatty(2)) == 0)).tap do |f| f.flush_on_newline = true end
STDIN = IO::FileDescriptor.new(0, blocking: (LibC.isatty(0)) == 0)
STDOUT = (IO::FileDescriptor.new(1, blocking: (LibC.isatty(1)) == 0)).tap do |f| f.flush_on_newline = true end

Method Summary

Macro Summary

Instance methods inherited from module Spec::Methods

assert(file = __FILE__, line = __LINE__, end_line = __END_LINE__, &block) assert, context(description, file = __FILE__, line = __LINE__, &block) context, describe(description, file = __FILE__, line = __LINE__, &block) describe, fail(msg, file = __FILE__, line = __LINE__) fail, it(description = "assert", file = __FILE__, line = __LINE__, end_line = __END_LINE__, &block) it, pending(description = "assert", file = __FILE__, line = __LINE__, end_line = __END_LINE__, &block) pending

Instance methods inherited from module Spec::Expectations

be(value)
be
be
, be_close(expected, delta) be_close, 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 = nil, file = __FILE__, line = __LINE__, &block) forall T expect_raises, match(value) match, start_with(expected) start_with

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.

Example:

`echo hi` # => "hi\n"

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

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


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

Registers the given Proc for execution when the program exits. 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.


[View source]
def caller #

[View source]
def delay(delay, &block : -> _) #

Spawns a Fiber to compute &block in the background after delay has elapsed. Access to get is synchronized between fibers. &block is only called once. May be canceled before &block is called by calling cancel.

d = delay(1) { Process.kill(Signal::KILL, Process.pid) }
# ... long operations ...
d.cancel

[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 fork #

See also: Process.fork


[View source]
def fork(&block) #

See also: Process.fork


[View source]
def future(&exp : -> _) #

Spawns a Fiber to compute &block in the background. Access to get is synchronized between fibers. &block is only called once.

f = future { `echo hello` }
# ... other actions ...
f.get # => "hello\n"

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

Reads a line from STDIN.

See also: IO#gets.


[View source]
def lazy(&block : -> _) #

Conditionally spawns a Fiber to run &block in the background. Access to get is synchronized between fibers. &block is only called once. &block doesn't run by default, only when get is called.

l = lazy { expensive_computation }
spawn { maybe_use_computation(l) }
spawn { maybe_use_computation(l) }

[View source]
def loop(&block) #

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.


[View source]
def p #

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 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 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 #

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 pp(object) #

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

See also: 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) : Nil #

Prints a formatted string to STDOUT.

For details on the format string, see sprintf.


[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 puts(*objects) : Nil #

Prints objects to STDOUT, each followed by 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 catched 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 #

See Random#rand.


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

Reads a line from STDIN.

See also: IO#read_line.


[View source]
def sleep #

Blocks the current fiber forever.

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


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

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(seconds : Number) #

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.


[View source]
def spawn(*, name : String? = nil, &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
    puts 1
  end
  ch.send(nil)
end

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

2.times { ch.receive }

[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 syntax for a format specifier is:

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

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

The field type controls how the corresponding sprintf argument 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 is consisted from optional sign, "0x", fraction part
          | as hexadecimal, "p", and exponential part as decimal.
      A   | Equivalent to a, but use uppercase X and P.

    Field |  Other Format
    ------+--------------------------------------------------------------
      c   | Argument is the numeric code for a single character or
          | a single character string itself.
      s   | Argument is a string to be substituted.  If the format
          | sequence contains a precision, at most that many characters
          | will be copied.
      %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:


  Flag     | Applies to    | Meaning
  ---------+---------------+-----------------------------------------
  space    | bdiouxX       | Add a leading space character to
           | aAeEfgG       | non-negative numbers.
           | (numeric fmt) | For o, x, X, b, use
           |               | a minus sign with absolute value for
           |               | negative values.
  ---------+---------------+-----------------------------------------
  +        | bdiouxX       | Add a leading plus sign to non-negative
           | aAeEfgG       | numbers.
           | (numeric fmt) | For o, x, X, b, use
           |               | a minus sign with absolute value for
           |               | negative values.
  ---------+---------------+-----------------------------------------
  -        | all           | Left-justify the result of this conversion.
  ---------+---------------+-----------------------------------------
  0 (zero) | bdiouxX       | Pad with zeros, not spaces.
           | aAeEfgG       | For o, x, X, b, radix-1
           | (numeric fmt) | is used for negative numbers formatted as
           |               | complements.

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 # => "-7B"

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"

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", 12  # => "+0000000000000000123"
sprintf "% 020d", 123 # => " 0000000000000000123"
sprintf "%-20d", 123  # => "123                 "
sprintf "%-+20d", 123 # => "+123                "
sprintf "%- 20d", 123 # => " 123                "
sprintf "%020x", -123 # => "00000000000000000-7b"
sprintf "%020X", -123 # => "00000000000000000-7B"

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   # => "                 123"
sprintf "%020.8d", 123  # => "00000000000000000123"
sprintf "%20.8o", 123   # => "                 173"
sprintf "%020.8o", 123  # => "00000000000000000173"
sprintf "%20.8x", 123   # => "                  7b"
sprintf "%020.8x", 123  # => "0000000000000000007b"
sprintf "%20.8b", 123   # => "            01111011"
sprintf "%20.8d", -123  # => "                -123"
sprintf "%020.8d", -123 # => "0000000000000000-123"
sprintf "%20.8o", -123  # => "                -173"
sprintf "%20.8x", -123  # => "                 -7b"
sprintf "%20.8b", -11   # => "               -1011"

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"

[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 syntax for a format specifier is:

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

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

The field type controls how the corresponding sprintf argument 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 is consisted from optional sign, "0x", fraction part
          | as hexadecimal, "p", and exponential part as decimal.
      A   | Equivalent to a, but use uppercase X and P.

    Field |  Other Format
    ------+--------------------------------------------------------------
      c   | Argument is the numeric code for a single character or
          | a single character string itself.
      s   | Argument is a string to be substituted.  If the format
          | sequence contains a precision, at most that many characters
          | will be copied.
      %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:


  Flag     | Applies to    | Meaning
  ---------+---------------+-----------------------------------------
  space    | bdiouxX       | Add a leading space character to
           | aAeEfgG       | non-negative numbers.
           | (numeric fmt) | For o, x, X, b, use
           |               | a minus sign with absolute value for
           |               | negative values.
  ---------+---------------+-----------------------------------------
  +        | bdiouxX       | Add a leading plus sign to non-negative
           | aAeEfgG       | numbers.
           | (numeric fmt) | For o, x, X, b, use
           |               | a minus sign with absolute value for
           |               | negative values.
  ---------+---------------+-----------------------------------------
  -        | all           | Left-justify the result of this conversion.
  ---------+---------------+-----------------------------------------
  0 (zero) | bdiouxX       | Pad with zeros, not spaces.
           | aAeEfgG       | For o, x, X, b, radix-1
           | (numeric fmt) | is used for negative numbers formatted as
           |               | complements.

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 # => "-7B"

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"

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", 12  # => "+0000000000000000123"
sprintf "% 020d", 123 # => " 0000000000000000123"
sprintf "%-20d", 123  # => "123                 "
sprintf "%-+20d", 123 # => "+123                "
sprintf "%- 20d", 123 # => " 123                "
sprintf "%020x", -123 # => "00000000000000000-7b"
sprintf "%020X", -123 # => "00000000000000000-7B"

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   # => "                 123"
sprintf "%020.8d", 123  # => "00000000000000000123"
sprintf "%20.8o", 123   # => "                 173"
sprintf "%020.8o", 123  # => "00000000000000000173"
sprintf "%20.8x", 123   # => "                  7b"
sprintf "%020.8x", 123  # => "0000000000000000007b"
sprintf "%20.8b", 123   # => "            01111011"
sprintf "%20.8d", -123  # => "                -123"
sprintf "%020.8d", -123 # => "0000000000000000-123"
sprintf "%20.8o", -123  # => "                -173"
sprintf "%20.8x", -123  # => "                 -7b"
sprintf "%20.8b", -11   # => "               -1011"

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"

[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 with_color(color : Symbol) #

[View source]
def with_color #

[View source]

Macro Detail

macro assert_responds_to(var, method) #

[View source]
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 parallel(*jobs) #

Runs the commands passed as arguments concurrently (in Fibers) and waits for them to finish.

def say(word)
  puts word
end

# Will print out the three words concurrently
parallel(
  say("concurrency"),
  say("is"),
  say("easy")
)

Can also be used to conveniently collect the return values of the concurrent operations.

def concurrent_job(word)
  word
end

a, b, c =
  parallel(
    concurrent_job("concurrency"),
    concurrent_job("is"),
    concurrent_job("easy")
  )

puts a # => "concurrency"
puts b # => "is"
puts c # => "easy"

Due to the concurrent nature of this macro, it is highly recommended to handle any exceptions within the concurrent calls. Unhandled exceptions raised within the concurrent operations will be re-raised inside the parent fiber as ConcurrentExecutionException, with the cause attribute set to the original exception.


[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, *properties) #

Defines a Struct with the given name and 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.

The properties can be type declarations or assignments.

You can pass a block to this macro, that will be inserted inside the struct definition.

record Point, x : Int32, y : Int32

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

An example with the block version:

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) #

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]