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.
Hello, world
Section titled “Hello, world”For now, programs start at a top-level main method.
puts "Hello, world!"def main: Void puts "Hello, world!"endTypes 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.
def greet(name, greeting: "Hello") "#{greeting}, #{name}!"end
greet("Ada", greeting: "Kia ora")def greet(name: String, greeting:: String = "Hello"): String "#{greeting}, #{name}!"end
greet("Ada", greeting: "Kia ora")nil has to be invited
Section titled “nil has to be invited”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.
user = find_user(id)puts user.name if usercity = user&.address&.city
user.name # NoMethodError at 3amuser = find_user(id) # User?puts user.name if user # narrowed to Usercity = user&.address&.city # String?
user.name # compile error: user may be nilTruthiness, with fewer surprises
Section titled “Truthiness, with fewer surprises”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.
puts "has items" if items.length # always true, even for 0puts "has items" if items.length > 0? and !
Section titled “? and !”? 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.
Classes
Section titled “Classes”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.
class User attr_accessor :name attr_reader :age
def initialize(name, age) @name = name @age = age end
def self.guest new("Guest", 0) endendclass 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) endenddef 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
Section titled “Blocks”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.
def apply(items, &block) items.map(&block)enddef apply(items: Array[Int], &block: (Int) -> Int): Array[Int] items.map(&block)endDSLs without instance_eval
Section titled “DSLs without instance_eval”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.
def html(&block) builder = HtmlBuilder.new builder.instance_eval(&block) builder.to_senddef html(&block: () -> Void with HtmlBuilder): String builder = HtmlBuilder.new yield builder builder.to_sendCallers 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.
Modules, split three ways
Section titled “Modules, split three ways”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 |
Metaprogramming
Section titled “Metaprogramming”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.
Everything else
Section titled “Everything else”| 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 |