Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created August 31, 2022 00:10
Show Gist options
  • Save havenwood/fb7cae67c2ee9979f2cbe8c98dc43d27 to your computer and use it in GitHub Desktop.
Save havenwood/fb7cae67c2ee9979f2cbe8c98dc43d27 to your computer and use it in GitHub Desktop.
Rust-inspired `struct` and `impl` in Ruby for fun
require_relative 'kernel'
struct :Point do
{
x: 0,
y: 0,
z: 0
}
end
impl :Point do
def to_s
"(#{x}, #{y}, #{z})"
end
end
point = Point.new
#=> #<struct Point x=0, y=0, z=0>
puts point
#>> (0, 0, 0)
module Kernel
def struct(class_name, &block)
pairs = block.call
struct = Struct.new(*pairs.keys, keyword_init: true)
const = Object.const_set(class_name, struct)
defaults = pairs.compact
if defaults.any?
const.class_eval do
define_method :initialize do
super(**defaults)
end
end
end
end
def impl(class_name, &block)
const = if Object.const_defined?(class_name)
Object.const_get(class_name)
else
Object.const_set(class_name, Class.new)
end
const.class_eval(&block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment