Struct lets me create a new class that takes arguments and has some nice semantics. However, the arguments aren't required, and their order requires consulting the definition:
Point = Struct.new(:x, :y)
Point.new(111, 222)
#=> <point instance with x = 111, y = 222>
Point.new(111)
#=> <point instance with x = 111, y = nil>
I'd like something similar to a Struct, but which uses keyword arguments instead:
Point = StricterStruct.new(:x, :y)
Point.new(x: 111, y: 222)
#=> <point instance with x = 111, y = 222>
Point.new(x: 111)
#=> ArgumentError
That might look something like this:
module StricterStruct
def self.new(*attributes)
klass = Class.new
klass.instance_eval { ... }
klass
end
end
But what should go in the braces to define an initialize method on klass such that:
- it requires keyword arguments with no default value;
- the keywords are given as an array of symbols in
attributes; and - the
initializemethod assigns them to instance variables of the same name