I’d like to create a Struct[1] from an array containing symbols representing the attributes of the Struct but can’t get it to work:
···
~~~
arr = [:attr1, :attr2, :attr3]
s = Struct.new(arr)
# => TypeError: no implicit conversion of Array into String
~~~
I’ve tried different conversions (to_s, etc.) and OpenStruct[2], too. Even though the latter is supposed to work dynamically it needs a hash and does not work with my array of symbols:
~~~
os = OpenStruct.new(arr)
# => NoMethodError: undefined method `each_pair’ for [:attr1, :attr2, :attr3]:Array
os = OpenStruct.new
os.arr[1]
# => NoMethodError: undefined method `[]' for nil:NilClass
~~~
Any ideas on how I can feed in my array of symbols into Struct.new or an OpenStruct?
I can't test it out from my phone but maybe try using the Splat operator?
arr = [:attr1, :attr2, :attr3]
s = Struct.new(*arr)
···
On Thu, Jan 12, 2017, 12:06 AM Michael Schwarze <michael@schwarze-web.de> wrote:
Hello!
I’d like to create a Struct[1] from an array containing symbols
representing the attributes of the Struct but can’t get it to work:
~~~
arr = [:attr1, :attr2, :attr3]
s = Struct.new(arr)
# => TypeError: no implicit conversion of Array into String
~~~
I’ve tried different conversions (to_s, etc.) and OpenStruct[2], too. Even
though the latter is supposed to work dynamically it needs a hash and does
not work with my array of symbols:
~~~
os = OpenStruct.new(arr)
# => NoMethodError: undefined method `each_pair’ for [:attr1, :attr2,
:attr3]:Array
os = OpenStruct.new
os.arr[1]
# => NoMethodError: undefined method `' for nil:NilClass
~~~
Any ideas on how I can feed in my array of symbols into Struct.new or an
OpenStruct?