I'm learning crystal (just for fun) and trying to implement kind of []=
method for a struct. Here is the first attempt:
struct Foo
@str : String | Int32 # Have to share all the types, NOT OK
@int : Int32 | String # Have to share all the types, NOT OK
def initialize(@str = "foo", @int = 111)
end
def []=(variable, value)
{% for ivar in @type.instance_vars %}
@{{ivar}} = value if {{ivar.id.symbolize}} == variable
{% end %}
end
end
foo = Foo.new
foo[:str] = "bar" # OK
foo[:int] = 222 # OK
It works, but the disadvantage is all the instance variables should share the same type, otherwise the compiller will complain. My second attempt was to reimplement the method like this:
def []=(variable, value)
{% for ivar in @type.instance_vars %}
{% if ivar.id.symbolize == variable %} # ERROR: undefined macro variable 'variable'
@{{ivar}} = value
{% end %}
{% end %}
end
But this doesn't work, as variable
inside {%%}
syntax can't be resolved. How to overcome this problem? Maybe there is other idiomatic approach to implement such method at all?