How to Dynamically Create Instance Variables in Ruby
akshaykhot.com
akshaykhot.com
Here’s an example: https://github.com/rubymonolith/demo/blob/main/app/controlle...
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...
I wonder if the language influences the aesthetics. Python is boring and clunky as well.
Some people here criticize meta-programming. I was one of them until I read the gorgeous Homebrew configuration files. Of course, don't overdo it.
I tried testing in Python years ago and found the likes of PyTest etc to be light years behind what RSpec and even Minitest offer.
It’s a reason I love Elixir.
The community does. You’ll notice that JavaScript command line tools are much fancier than other languages, with emojis and cool spinners. Being that many JS programmers are web developers there’s a sense of aesthetics baked in the community. Other communities don’t have to care about “pretty” in their day-to-day so their tools reflect it.
It's quite a bit problem for Python actually IMO. It is so popular among beginners that a lot of libraries and StackOverflow answers are beginner-quality.
In the case of Ruby, in fact the culture didn't come from Ruby, but Ruby on Rails, which marketed almost exclusively to non-programmers. "Classic" programmers suck at design.
Thanks for reading my highly technical analysis.
Make sure you absolutely need it
Trying to track variable names and finding specific code when they are being generated dynamically can quickly become nightmare
For example, it allows you to monkey patch at runtime any library that you install.
Compare with Javascript, i'm not sure if you can just install a package, patch it at runtime (like this article is about) to match your need.
In some sense, this is similar to OOP inheritance and overloading, but for intance variables.
That's why most of Ruby startups tends to go faster than other languages, because all Ruby classes is hackable at runtime.
var foo = {}
foo.bar = “hello new property”
console.log(foo.bar)
foo = {bar: "123"}; with (foo) eval("console.log(bar)")
I find that while Ruby’s syntax may have a smaller surface area there are so many more ways to do things than with other languages that I reach for others first.
Also Ruby encourages so much metaprogramming that it can be very very difficult to work out where a behavior comes from. You _really_ have to document everything and getting a good editor config for Ruby is very important. That said I still struggle to get basic autocomplete working with Ruby in vs code