Subject: Re: Creating a struct from an array of symbols



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 <[email protected]> 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?

Many thanks!

Cheers,
Michael


[1]: https://ruby-doc.org/core-2.4.0/Struct.html
[2]: https://ruby-doc.org/stdlib-2.4.0/libdoc/ostruct/rdoc/OpenStruct.html

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
--

- Raj


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>

Programming list archiving by: Enterprise Git Hosting