Skip to content

Instantly share code, notes, and snippets.

@MiniAppleTheApple
Last active July 4, 2025 21:49
Show Gist options
  • Select an option

  • Save MiniAppleTheApple/0e8c1e4950c48a1b697e1d148b833204 to your computer and use it in GitHub Desktop.

Select an option

Save MiniAppleTheApple/0e8c1e4950c48a1b697e1d148b833204 to your computer and use it in GitHub Desktop.
Record implementation in ruby
relative_require "record"
class Record
record :a, :b
end
a = Record.new(a: 10, b: 20)
a = a.merge(b: 10)
p a
def record(*attrs)
define_method('initialize') do |**args|
attrs.each {|key| instance_variable_set("@#{key}", args[key])}
end
define_method('merge') do |**args|
self.class.new **(instance_variables.map {|key| [key.slice(1).to_sym, instance_variable_get(key)]}.to_h.merge(args))
end
define_method('inspect') do ||
data_format = instance_variables.map {|key| "#{key} = #{instance_variable_get(key)}"}.join(", ")
"#{self.class.name}(#{data_format})"
end
attr_reader *attrs
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment