News for hackers. Stuff that matters.
Re:How to Dynamically Create Instance Variables in Ruby by psychoslave on Friday July 28, 2023 @03:16AM (#36903900)
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/OpenSt...

Re:How to Dynamically Create Instance Variables in Ruby by joshmcmillan on Friday July 28, 2023 @06:52AM (#36905119)
Ruby 3.2 has `Data.define`, which is an even better way of doing this: https://docs.ruby-lang.org/en/3.2/Data.html
Re:How to Dynamically Create Instance Variables in Ruby by psychoslave on Friday July 28, 2023 @07:50AM (#36905530)
Awesome, thanks for pointing it.
Re:How to Dynamically Create Instance Variables in Ruby by nerdponx on Friday July 28, 2023 @08:49AM (#36906054)
Nice, it's attrs/dataclass from Python.
Re:How to Dynamically Create Instance Variables in Ruby by nerdponx on Friday July 28, 2023 @08:52AM (#36906076)
This 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.