Ruby to Raku - nutshell

Learning Raku from Ruby, in a nutshell: what do I already know?

This page attempts to index the high-level differences in syntax and semantics between Ruby and Raku. Whatever works in Ruby and must be written differently in Raku should be listed here (whereas many Raku features and idioms won't be).

Hence this should not be mistaken for a beginner tutorial or overview of Raku; it is intended as a technical reference for Raku learners with a strong Ruby background.

Basic syntax

Statement ending semicolons

Ruby detects the end of most statements with a newline (and a few exceptions), as long as the expression is complete. It is common break up a long expression by leaving an operator dangling at the end of a line to ensure that the parsing will continue:

foo +     # In Ruby a trailing operator means parsing should continue 
  bar +

In Raku you must explicitly terminate statements with a ;, which allows for better feedback and more flexibility in breaking up long lines. Two exceptions not needing an explicit ; are the last statement in a block, and after the closing curly brace of the block itself (if there is nothing else on that line):

my $x;
if 5 < $x < 10 {
  say "Yep!";
  $x = 17         # No ; required before closing } 
}                 # No ; required after closing } because of the newline 
say "Done!";      # The ; is not required here if nothing follows


Ruby allows a surprising amount of flexibility in the use of whitespace, even with strict mode and warnings turned on:

# unidiomatic but valid Ruby 
puts"Hello "+
(people [ i]
    . name
    ) . upcase+"!"if$greeted[i]<1

Raku also endorses programmer freedom and creativity, but balanced syntactic flexibility against its design goal of having a consistent, deterministic, extensible grammar that supports single-pass parsing and helpful error messages, integrates features like custom operators cleanly, and doesn't lead programmers to accidentally misstate their intent. Also, the practice of "code golf" is slightly de-emphasized; Raku is designed to be more concise in concepts than in keystrokes.

As a result, there are various places in the syntax where whitespace is optional in Ruby, but is either mandatory or forbidden in Raku. Many of those restrictions are unlikely to concern much real-life Perl code (e.g. whitespace being disallowed between an array variable and its square brackets), but there are a few that will unfortunately conflict with some Ruby hackers' habitual coding styles:

if(a < 0); ...end         # OK in Ruby 
my $a...;
if ($a < 0{ ... }         # Raku 
if $a < 0 { ... }           # Raku, more idiomatic 
while(x > 5); ...end      # OK in Ruby 
my $x...;
while ($x > 5{ ... }      # Raku 
while $x > 5 { ... }        # Raku, more idiomatic 

. Method calls, .public_send

Method call syntax uses a dot just like Ruby:    # Ruby 
my $person...;
$   # Raku 

To call a method whose name is not known until runtime:

object.public_send(methodnameargs);  # Ruby 
my $objectmy Str $methodnamemy @args...;
$object."$methodname"(@args);   # Raku 

If you leave out the quotes, then Raku expects $methodname to contain a Method object, rather than the simple string name of the method.

Variables, sigils, scope, and common types

In Ruby, variables use sigils primarily to indicate scope. $ for global scope, @@ for class scope, @ for instance scope, and no sigil for local variables (including parameters). The & sigil is also used to indicate method references. Symbols are prefixed with :, but they are not variable and so not really sigils.

In Raku sigils are primarily used to indicate a role that the contained value implements, indicating the type (or at least the interface) of the value. The sigils are invariant, no matter how the variable is being used - you can think of them as part of the variable's name.

The scope of a variable is instead indicated by the declaration itself (my, has, our, etc).

Variable scope

For local variables, Ruby uses implicit variable declaration upon assignment and limited to the current block. In Ruby the content of an if or while built-in construct is not a block or scope.

Raku uses explicit scope indicators, and never creates variables implicitly. Every place you see { ... } is a scope, including the body of a conditional or loop. The commonly used scope declarations:

foo = 7        # Ruby, variable scope is defined by first assignment and 
               # extends to the end of the current block 
my  $foo = 7;   # Raku, lexical scoped to the current block 
our $foo = 7;   # Raku, package scoped 
has $!foo = 7;  # Raku, instance scoped (attribute) 

$ Scalar

The $ sigil is always used with "scalar" variables (e.g. $name). These are single-value containers.

This is the most general-purpose variable type, with no restrictions on its contents. Note that you can still address/use its contents, like $x[1], $x{"foo"}, and $f("foo").

@ Array

The @ sigil is always used with "array" variables (e.g. @months, @months[2], @months[2, 4] for an array slice). Variables using the @ sigil can only contain things that do the Positional role, indicating positional indexing and slicing capabilities.

% Hash

The % sigil is always used with "hash" variables (e.g. %calories, %calories<apple>, %calories<pear plum>). Variables using the % sigil can only contain things that do the Associative role.

Ruby uses square brackets to access values for both Arrays and Hashes. Raku uses curly braces for hashes instead. The angle brackets version is available which always autoquotes its contents (strings without quotes):

Adverbs can be used to control the type of slice.

& Sub

The & sigil is used very similarly to Ruby's & to refer to the function object of a named subroutine/operator without invoking it, i.e. to use the name as a "noun" instead of a "verb". Variables using the & sigil can only contain things that do the Callable role.

add = -> n, m { n + m } # Ruby lambda for an addition function 
add.(23)              # => 5, Ruby invocation of a lambda          # => 5, Ruby invocation of a lambda 
my &add = -> $n$m { $n + $m }# Raku addition function 
&add(23);                      # => 5, you can keep the sigil 
add(23);                       # => 5, and it works without it 
def foo
foo_method = method(:foo);     # Ruby 
sub foo { ... };
my &foo_method = &foo# Raku 
some_func(&say# Ruby pass a function reference 
sub some_func { ... };
some_func(&say# Raku passes function references the same way 

Often in Ruby we pass a block as the last parameter, which is especially used for DSLs. This can be an implicit parameter called by yield, or an explicit block prefixed with &. In Raku a Callable parameter is always listed and called by the variable name (instead of yield), and there are a variety of ways of invoking the function.

# Ruby, declare a method and call the implicit block argument 
def f
  yield 2
# Ruby, invoke f, pass it a block with 1 argument 
f do |n|
  puts "Hi #{n}"
# Raku, declare a method with an explicit block argument 
sub f(&g:($)) {
# Raku, invoke f, pass it a block with 1 argument 
# There are several other ways to do this 
f(-> $n { say "Hi {$n}" }); # Explicit argument 
f -> $n { say "Hi {$n}" };  # Explicit argument, no parenthesis 
# Additionally, if 'f' is a method on instance 'obj' you can use ':' 
# instead of parenthesis 
my $obj...;
$obj.f(-> $n { say "Hi {$n}" });  # Explicit argument 
$obj.f: -> $n { say "Hi {$n}" };  # Explicit argument, no parenthesis 

* Slurpy params / argument expansion

In Ruby you can declare an argument to slurp the remainder of the passed parameters into an array using a * prefix. It works similarly in Raku:

def foo(*args); puts "I got #{args.length} args!"end # Ruby 
sub foo(*@args{ say "I got #{@args.elems} args!" }   # Raku 

The Raku version above is slightly different in that when it slurps in the arguments into @args, one level of nesting, if any, is automatically removed:

sub foo(*@args{ say @args.raku }
foo([1, [23], 4], 5, [67]);   # [1, [2, 3], 4, 5, 6, 7] 

To preserve the structure of the arguments, you can use **:

sub foo(**@args{ say @args.raku }
foo([1, [23], 4], 5, [67]);  # [[1, [2, 3], 4], 5, [6, 7]] 

You might want to expand an array into a set of arguments. In Raku this is done using a Slip |:

args = %w(a b c)         # Ruby 
sub foo($q$r$s{ ... };
my @args = <a b c>;       # Raku 

Raku has many more advanced ways of passing parameters and receiving arguments, see Signatures and Captures.


Raku additionally uses "twigils", which are further indicators about the variable and go between the sigil and the rest of the variable name. Examples:

Variable Description
$foo Scalar with no twigil
$!foo Private instance variable
$.foo Instance variable accessor
$*foo Dynamically scoped variable
$^foo A positional (placeholder) parameter to a block
$:foo A named (placeholder) parameter to a block
$=foo POD (documentation) variables
$?FILE Current source filename. The ? twigil indicates a compile-time value
$~foo Sublanguage seen by parser, uncommon

Though each of these examples use the $ sigil, most could use @ (Positional) or % (Associative).

: Symbols

Raku generally uses strings in the places where Ruby uses symbols. A primary example of this is in hash keys.

address[:joe][:street# Typical Ruby nested hash with symbol keys 
my %address...;
%address<joe><street>  # Typical Raku nested hash with string keys 

Raku has colon-pair syntax, which can sometimes look like Ruby symbols.

:age            # Ruby symbol 
# All of these are equivalent for Raku 
:age            ;# Raku pair with implicit True value 
:age(True)      ;# Raku pair with explicit True value 
age => True     ;# Raku pair using arrow notation 
"age" => True   ;# Raku pair using arrow notation and explicit quotes 

You could probably get away with using a colon-pair without an explicit value and pretend that it is a Ruby symbol a lot of the time, but it isn't idiomatic Raku.


Many operators have a similar usage in both Ruby and Raku:

You may use $x++ instead of x += 1 as a shortcut for incrementing a variable. This can be used as a pre-increment ++$x (increment, return new value) or post-increment $x++ (increment, return old value).

You may use $x-- instead of x -= 1 as a shortcut for decrementing a variable. This can be used as a pre-decrement --$x (decrement, return new value) or post-decrement $x-- (decrement, return old value).

== != < > <= >= Comparisons

Comparisons in Raku are separated between numeric and string to avoid common errors.

For example, using == tries to convert the values to numbers, and eq tries to convert the values to strings.

<=> Three-way comparisons

In Ruby, the <=> operator returns -1, 0, or 1. In Raku, they return Order::Less, Order::Same, or Order::More.

<=> forces numeric context for the comparison.

leg ("Less, Equal, or Greater?") forces string context for the comparison.

cmp does either <=> or leg, depending on the existing type of its arguments.

~~ Smartmatch operator

This is a very common matching operator which is similar to === in Ruby. Here are some examples:

my $foo...;
say "match!" if $foo ~~ /bar/;       # Regex match 
say "match!" if $foo ~~ "bar";       # String match 
say "match!" if $foo ~~ :(IntStr); # Signature match (destructure)

An equivalent in Ruby would be

$foo = 'bar';
puts "match 1!" if /bar/ === $foo;       # Regex match 
puts "match 2!" if $foo === "bar";       # String match 
puts "match 3!" if String === $foo;      # Class match 

Please note that, in this case, === is not symmetric; in the first and last case, the variable has to be in the right-hand side. There is no equivalent to the signature class in Ruby, either.

See S03/Smartmatching for more information on this feature.

& | ^ Numeric bitwise ops

& | ^ Boolean ops

In Raku, these single-character ops have been removed, and replaced by two-character ops which coerce their arguments to the needed context.

# Infix ops (two arguments; one on each side of the op) 
+&  +|  +^  And Or Xor: Numeric
~&  ~|  ~^  And Or Xor: String
?&  ?|  ?^  And Or Xor: Boolean
# Prefix ops (one argument, after the op) 
+^  Not: Numeric
~^  Not: String
?^  Not: Boolean (same as the ! op)

&. Conditional chaining operator

Ruby uses the &. operator to chain methods without raising an error if one invocation returns nil. In Raku use .? for the same purpose.

<< >> Numeric shift left, right ops, shovel operator

Replaced by +< and +> .

puts 42 << 3  # Ruby 
say  42 +< 3# Raku 

Note that Ruby often uses the << operator as the "shovel operator", which is similar to .push. This usage isn't common in Raku.

=> and : Key-value separators

In Ruby, => is used in the context of key/value pairs for Hash literal declaration and parameter passing. : is used as a shorthand when the left side is a symbol.

In Raku, => is the Pair operator, which is quite different in principle, but works the same in many situations.

If you are using => in a hash literal, then the usage is very similar:

hash = { "AAA" => 1"BBB" => 2 }  # Ruby, though symbol keys are more common 
my %hash = ( AAA => 1BBB => 2 ); # Raku, uses ()'s though {} usually work 

? : Ternary operator

In Raku, this is spelled with two question marks instead of one question mark, and two exclamation points instead of one colon. This deviation from the common ternary operators disambiguates several situations and makes the false-case stand out more.

result     = (  score > 60 )  ? 'Pass'  : 'Fail'# Ruby 
my $score...;
my $result = ( $score > 60 ) ?? 'Pass' !! 'Fail'# Raku 

+ String concatenation

Replaced by the tilde. Mnemonic: think of "stitching" together the two strings with needle and thread.

$food = 'grape' + 'fruit'  # Ruby 
my $food = 'grape' ~ 'fruit'# Raku 

String interpolation

In Ruby, "#{foo}s" deliminates a block embedded in a double-quoted string. In Raku drop the # prefix: "{$foo}s". As in Ruby, you can place arbitrary code into the embedded block and it will be rendered in string context.

Simple variables can be interpolated into a double-quoted string without using the block syntax:

# Ruby 
name = "Bob"
puts "Hello! My name is #{name}!"
# Raku 
my $name = "Bob";
say "Hello! My name is $name!"

The result of an embedded block in Ruby uses .to_s to get string context. Raku uses .Str, or .gist for the same affect.

Compound statements


if elsif else unless

This work very similarly between Ruby and Raku, but Raku uses { } to clearly delineate the blocks.

# Ruby 
if x > 5
    puts "Bigger!"
elsif x == 5
    puts "The same!"
    puts "Smaller!"
# Raku 
my $x...;
if $x > 5 {
    say "Bigger!"
} elsif $x == 5 {
    say "The same!"
} else {
    say "Smaller!"

Binding the conditional expression to a variable is a little different:

if x = dostuff(); ...end   # Ruby 
sub dostuff() {...};
if dostuff() -> $x {...}     # Raku, block-assignment uses arrow 

The unless conditional only allows for a single block in Raku; it does not allow for an elsif or else clause.


The Raku given-when construct is like a chain of if-elsif-else statements, and its direct analog is Ruby's case-when construct. Just as Ruby uses the === (case equality) operator for each condition in a case-when expression, Raku, likewise, uses the smartmatch ~~ operator with given-when.

It has the general structure:

given EXPR {
    when EXPR { ... }
    when EXPR { ... }
    default { ... }

In its simplest form, the construct is as follows:

my $value...;
given $value {
    when "a match" {
        # do-something(); 
    when "another match" {
        # do-something-else(); 
    default {
        # do-default-thing(); 

This is simple in the sense that a scalar value is matched in the when statements. More generally, the matches are actually smartmatches on the input value such that lookups using more complex entities such as regexps can be used instead of scalar values.


while until

Mostly unchanged; parentheses around the conditions are optional, but if used, must not immediately follow the keyword, or it will be taken as a function call instead. Binding the conditional expression to a variable is also a little different:

while x = dostuff(); ...end    # Ruby 
sub dostuff {...}...;
while dostuff() -> $x {...}      # Raku 

for .each

for loops are rare in Ruby, instead we typically use .each on an enumerable. The most direct translation to Raku would be to use .map for both .each and .map, but we typically use a for loop directly.

# Ruby for loop 
for n in 0..5
    puts "n: #{n}"
# Ruby, more common usage of .each 
(0..5).each do |n|
    puts "n: #{n}"
# Raku 
for 0..5 -> $n {
    say "n: $n";
# Raku, misusing .map 
(0..5).map: -> $n {
    say "n: $n";

In Ruby, the iteration variable for .each is a copy of the list element, and modifying it does nothing to the original list. Note that it is a copy of the REFERENCE, so you can still change the values to which it refers.

In Raku, that alias is read-only (for safety) and thus behaves exactly like Ruby, unless you change -> to <->.

cars.each { |car| ... }    # Ruby; read-only reference 
my @cars...;
for @cars  -> $car   {...} # Raku; read-only 
for @cars <-> $car   {...} # Raku; read-write 

Flow interruption statements

Same as Ruby:

This is last in Raku.

Regular expressions ( regex / regexp )

Regular expressions in Raku are significantly different, and more powerful, than in Ruby. By default whitespace is ignored and all characters must be escaped, for example. Regexes can be easily combined and declared in ways to build efficient grammars.

There are many powerful features of Raku regexes, especially defining entire grammars using the same syntax. See Regexes and Grammars.

.match method and =~ operator

In Ruby, regex matches can be done against a variable using the =~ regexp match operator or the .match method. In Raku, the ~~ smartmatch op is used instead, or the .match method.

next if line   =~ /static/   # Ruby 
next if line  !~  /dynamic/# Ruby 
next if line.match(/static/# Ruby 
my $line...;
next if $line  ~~ /static/;    # Raku 
next if $line !~~ /dynamic/ ;  # Raku 
next if $line.match(/static/); # Raku 

Alternately, the .match and .subst methods can be used. Note that .subst is non-mutating. See S05/Substitution.

.sub and .sub!

In Raku you typically use the s/// operator to do regex substitution.

fixed = line.sub(/foo/'bar')        # Ruby, non-mutating 
my $line...;
my $fixed = $line.subst(/foo/'bar'# Raku, non-mutating 
line.sub!(/foo/'bar')   # Ruby, mutating 
my $line...;
$line ~~ s/foo/bar/;      # Raku, mutating 

Regex options

Move any options from the end of the regex to the beginning. This may require you to add the optional m on a plain match like /abc/.

next if $line =~    /static/i # Ruby 
my $line...;
next if $line ~~ m:i/static/# Raku 

Whitespace is ignored, most things must be quoted

In order to aid in readability and reusability, whitespace is not significant in Raku regexes.

/this is a test/ # Ruby, boring string 
/this.*/         # Ruby, possibly interesting string 
/ this " " is " " a " " test /# Raku, each space is quoted 
/ "this is a test" /;           # Raku, quoting the whole string 
/ this .* /;                    # Raku, possibly interesting string 

Special matchers generally fall under the <> syntax

There are many cases of special matching syntax that Raku regexes support. They won't all be listed here, but often instead of being surrounded by (), the assertions will be surrounded by <>.

For character classes, this means that:

For look-around assertions:

(Unrelated to <> syntax, the "lookaround" /foo\Kbar/ becomes /foo <( bar )> /

Longest token matching (LTM) displaces alternation

In Raku regexes, | does Longest Token Match (LTM), which decides which alternation wins an ambiguous match based off of a set of rules, rather than about which was written first in the regex.

To avoid the new logic, change any | in your Ruby regex to a ||.

File-related operations

Reading the lines of a text file into an array

Both Ruby and Raku make it easy to read all of the lines in a file into a single variable, and in both cases each line has the newline removed.

lines = File.readlines("file")   # Ruby 
my @lines = "file".IO.lines;     # Raku, create an IO object from a string 

Iterating over the lines of a text file

Reading the entire file into memory isn't recommended. The .lines method in Raku returns a lazy sequence, but assigning to an array forces the file to be read. It is better to iterate over the results:

# Ruby 
File.foreach("file"do |line|
    puts line
# Raku 
for "file".IO.lines -> $line {
    say $line

Object orientation

Basic classes, methods, attributes

Classes are defined similarly between Ruby and Raku, using the class keyword. Ruby uses def for methods, whereas Raku uses method.

# Ruby 
class Foo
    def greet(name)
        puts "Hi #{name}!"
# Raku 
class Foo {
    method greet($name{
        say "Hi $name!"

In Ruby you can use an attribute without declaring it beforehand, and you can tell it is an attribute because of the @ sigil. You can also easily create accessors using attr_accessor and its variants. In Raku you use a has declaration and a variety of sigils. You can use the ! twigil for private attributes or . to create an accessor.

# Ruby 
class Person
    attr_accessor :age    # Declare .age as an accessor method for @age 
    def initialize
        @name = 'default' # Assign default value to private instance var 
# Raku 
class Person {
    has $.age;              # Declare $!age and accessor methods 
    has $!name = 'default'# Assign default value to private instance var 

Creating a new instance of the class uses the .new method. In Ruby you must manually assign instance variables as needed inside initialize. In Raku you get a default constructor that accepts key/value pairs of accessor attributes, and can do further setup in the TWEAK method. Like with Ruby, you can override new itself for more advanced functionality, but this is rare.

# Ruby 
class Person
    attr_accessor :name:age
    def initialize(attrs)
        @name = attrs[:name|| 'Jill'
        @age  = attrs[:age|| 42
        @birth_year = - @age
p = Person.newname: 'Jack'age: 23 )
# Raku 
class Person {
    has $.name = 'Jill';
    has $.age  = 42;
    has $.birth_year;
    method TWEAK {
        $!birth_year = now.Date.year - $!age;
my $p = Person.newname => 'Jack'age => 23 )

Private methods

Private methods in Raku are declared with a ! prefixed in their name, and are invoked with a ! instead of a ..

# Ruby 
class Foo
    def visible
        puts "I can be seen!"
    def hidden
        puts "I cannot easily be called!"
# Raku 
class Foo {
    method visible {
        say "I can be seen!";
    method !hidden {
        say "I cannot easily be called!";

An important note is that in Ruby child objects can see parent private methods (so they are more like "protected" methods in other languages). In Raku child objects cannot call parent private methods.

Going meta

Here are a few examples of metaprogramming. Note that Raku separates the metamethods from the regular methods with a caret.

# Ruby 
person =
# Raku 
class Person {};
my $person =;
$person.^name;             # Raku, returns Person (class) 
$person.^methods;          # Raku, using .^ syntax to access metamethods 

Like Ruby, in Raku, everything is an object, but not all operations are equivalent to .public_send. Many operators are global functions that use typed multi-dispatch (function signatures with types) to decide which implementation to use.

5.public_send(:+3)    # => 8, Ruby 
&[+](53)       # => 8, Raku, reference to infix addition operator 
&[+].^candidates # Raku, lists all signatures for the + operator 

See Metaobject Protocol for lots of further details.

Environment variables

Raku module library path

In Ruby, one of the environment variables to specify extra search paths for modules is RUBYLIB.

$ RUBYLIB="/some/module/lib" ruby program.rb

In Raku this is similar, you merely needs to change the name. As you probably guessed, you just need to use RAKULIB:

$ RAKULIB="/some/module/lib" raku program.raku

As with Ruby, if you don't specify RAKULIB, you need to specify the library path within the program via the use lib pragma:

# Ruby and Raku 
use lib '/some/module/lib';


Importing specific functions from a module

In Ruby there is no built-in way to selectively import/export methods from a module.

In Raku you specify the functions which are to be exported by using the is export role on the relevant subs and all subs with this role are then exported. Hence, the following module Bar exports the subs foo and bar but not baz:

unit module Bar# remainder of the file is in module Bar { ... } 
sub foo($ais export { say "foo $a" }
sub bar($bis export { say "bar $b" }
sub baz($z{ say "baz $z" }

To use this module, simply use Bar and the functions foo and bar will be available:

use Bar;
foo(1);    #=> "foo 1" 
bar(2);    #=> "bar 2" 

If you try to use baz an "Undeclared routine" error is raised at compile time.

Some modules allow for selectively importing functions, which would look like:

use Bar <foo># Import only foo 
foo(1);        #=> "foo 1" 
bar(2);        # Error! 

OptionParser, parsing command-line flags

Command line argument switch parsing in Raku is done by the parameter list of the MAIN subroutine.

# Ruby 
require 'optparse'
options = {} do |opts|
    opts.banner = 'Usage: example.rb --length=abc'
    opts.on("--length""Set the file"do |length|
        raise "Length must be > 0" unless length.to_i > 0
        options[:length= length
    opts.on("--filename""Set the file"do |filename|
        options[:file= filename
    opts.on("--verbose""Increase verbosity"do |verbose|
        options[:verbose= true
puts options[:length]
puts options[:filename]
puts 'Verbosity ', (options[:verbose? 'on' : 'off')
ruby example.rb --filename=foo --length=42 --verbose
    Verbosity on
ruby example.rb --length=abc
    Length must be > 0
# Raku 
sub MAIN ( Int :$length where * > 0:$filename = 'file.dat'Bool :$verbose ) {
    say $length;
    say $filename;
    say 'Verbosity ', ($verbose ?? 'on' !! 'off');
raku example.p6 --file=foo --length=42 --verbose
    Verbosity on
raku example.p6 --length=abc
      example.p6 [--length=<Int>] [--file=<Any>] [--verbose]

Note that Raku auto-generates a full usage message on error in command-line parsing.

RubyGems, external libraries

See, where a growing number of Raku libraries are available along with the tools to manage them.

If the module that you were using has not been converted to Raku, and no alternative is listed in this document, then its use under Raku may not have been addressed yet.

You can experiment with Inline::Ruby to call existing Ruby code from your Raku programs. This uses an embedded instance of the ruby interpreter to run Ruby code called from your Raku script. Note that this is an EXPERIMENTAL library. You can similarly call other language's libraries with Inline::Perl5, Inline::Python, and others.