3 ms·
If you just need to pass data around in something more rigid than a hash, you can use a struct: someone = Struct.new(*%i[name age craze whatever]).new(?Ô, 12
by psychoslave 3y ago
If you just need to pass data around in something more rigid than a hash, you can use a struct:
someone = Struct.new(*%i[name age craze whatever]).new(?Ô, 128, {color: :pink}, :nevermind)
Or even an open struct for more flexibility, if performance is not critical and an additional require doesn’t matter.
https://ruby-doc.org/stdlib-3.1.0/libdoc/ostruct/rdoc/OpenStruct.html https://ruby-doc.org/stdlib-3.1.0/libdoc/ostruct/rdoc/OpenSt...
- joshmcmillan 3y agoRuby 3.2 has `Data.define`, which is an even better way of doing this: https://docs.ruby-lang.org/en/3.2/Data.html https://docs.ruby-lang.org/en/3.2/Data.html
- psychoslave 3y agoAwesome, thanks for pointing it.
- nerdponx 3y agoNice, it's attrs/dataclass from Python.
- nerdponx 3y agoThis seems infinitely better than dynamically adding instance attributes. Dynamic instance attributes was absolutely the worst thing about "old school" Python programming. The language, community, and ecosystem are much better off now that it's considered bad style and is strongly discouraged. Unfortunately we are stuck with it in the stdlib logging framework and the Tornado web framework, but it's mercifully absent just about everywhere else, and help platforms will almost universally discourage people from doing it.