Last active
July 4, 2025 21:49
-
-
Save MiniAppleTheApple/0e8c1e4950c48a1b697e1d148b833204 to your computer and use it in GitHub Desktop.
Record implementation in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| relative_require "record" | |
| class Record | |
| record :a, :b | |
| end | |
| a = Record.new(a: 10, b: 20) | |
| a = a.merge(b: 10) | |
| p a |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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