Skip to content

Amethyst for Ruby developers

Amethyst looks like Ruby on purpose: def/end, blocks, symbols, string interpolation, ? and ! methods, postfix if. Most of your instincts carry over.

The differences come from one decision: the compiler knows the type of everything before your program runs. Matz wanted programmers to be happy. I’d like them to be happy writing the code, and not bash their head in when they see undefined method 'save!' for nil. In exchange for writing some types down, you get errors at compile time, the speed of compiled .NET code, and the entire .NET ecosystem.

For now, programs start at a top-level main method.

Ruby
puts "Hello, world!"
Amethyst
def main: Void
puts "Hello, world!"
end

Types on methods, inference everywhere else

Section titled “Types on methods, inference everywhere else”

Method parameters and public return types are annotated. Local variables are inferred, as are the return types of private methods. Writing types is like flossing: mildly tedious, and you’ll be glad you did.

Ruby
def greet(name, greeting: "Hello")
"#{greeting}, #{name}!"
end
greet("Ada", greeting: "Kia ora")
Amethyst
def greet(name: String, greeting:: String = "Hello"): String
"#{greeting}, #{name}!"
end
greet("Ada", greeting: "Kia ora")

Types are non-nullable by default. User? means “a User or nil”, and the compiler won’t let you call methods on it until you’ve checked. &. works exactly as it does in Ruby.

Ruby
user = find_user(id)
puts user.name if user
city = user&.address&.city
user.name # NoMethodError at 3am
Amethyst
user = find_user(id) # User?
puts user.name if user # narrowed to User
city = user&.address&.city # String?
user.name # compile error: user may be nil

Only nil and false are falsy, as in Ruby. But if only accepts a Bool or a nullable value, so conditions that are always truthy don’t compile.

Ruby
puts "has items" if items.length # always true, even for 0
Amethyst
puts "has items" if items.length > 0

? methods must return Bool. ! methods raise on failure instead of returning nil or false, the convention Rails uses for save!, rather than marking an in-place mutation like upcase!.

For C# callers, valid? compiles to IsValid() and save! compiles to Save(). Because save! and save would both become Save(), defining both needs an @[Alias] to rename one of them. See .NET Naming Interop.

attr_accessor becomes property, attr_reader becomes getter, and attr_writer becomes setter, each with a type. Single inheritance with <, initialize, .new and def self. are all unchanged.

Ruby
class User
attr_accessor :name
attr_reader :age
def initialize(name, age)
@name = name
@age = age
end
def self.guest
new("Guest", 0)
end
end
Amethyst
class User
property name: String
getter age: Int
def initialize(name: String, age: Int)
@name = name
@age = age
end
def self.guest: User
User.new("Guest", 0)
end
end

def initialize(@name: String, @age: Int) declares and assigns both fields in one go. And protected follows C#: it means “this class and its subclasses”, not “any instance of this class”.

Blocks work the way you expect, including yield, &block, &:symbol and the return semantics: return leaves the enclosing method, and next leaves the block. A method that takes a block declares its type.

Ruby
def apply(items, &block)
items.map(&block)
end
Amethyst
def apply(items: Array[Int], &block: (Int) -> Int): Array[Int]
items.map(&block)
end

Ruby DSLs usually run their block with instance_eval, so self changes at runtime and nobody knows what’s callable until it’s called. In Amethyst, the method declares the receiver’s type with with, and the compiler checks every call in the block.

Ruby
def html(&block)
builder = HtmlBuilder.new
builder.instance_eval(&block)
builder.to_s
end
Amethyst
def html(&block: () -> Void with HtmlBuilder): String
builder = HtmlBuilder.new
yield builder
builder.to_s
end

Callers write exactly the same DSL. The only difference is that typos fail the build instead of raising NoMethodError from somewhere deep inside a gem. See Type-safe builders.

A Ruby module does several jobs. Amethyst gives each job its own keyword.

Ruby Amethyst
module Billing as a namespace namespace Billing
module Greetable with methods, then include mixin Greetable, then include
Duck typing: “anything with an each” protocol with implements
Reopening class String extension class String, visible only where it’s imported, much like a refinement

Classes can’t be changed while the program runs. Most of what Ruby does at runtime has a compile-time counterpart instead.

Ruby Amethyst
attr_accessor property, getter, setter
Monkey patching extension class. The monkeys are still welcome; they just have to stay in their own file
method_missing Opt in with include DynamicMessages
respond_to? responds_to? (respond_to? also works), usually answered at compile time
send send, which returns Any?
=== in case Not needed: when matches values, types and ranges directly

See Metaprogramming for the details.

Ruby Amethyst
[] [] when the type is clear, otherwise [] of String
{} {} of Symbol => String when the type isn’t clear
StandardError, RuntimeError .NET exceptions ending in Exception. raise "oops" raises a RuntimeException
begin/rescue/else/ensure/retry Unchanged
Gemfile project.am, managed with am add
Gems Any NuGet package. That’s a lot of gems
require "json" use System::Text::Json
CONSTANT = 1 ALL_CAPS = 1; constants are names in all caps