Everyone loves magic, right? If you’re a Rubyist, you pretty much have to love it. These week’s newsletter has a couple mentions of Ruby and magic, one about metaprogramming and one a tale of Docker and guards.
This week’s question is: What’s your favorite bit of Ruby magic? What about your least favorite? If you’re answer includes Rails, try to come up with at least one non-Rails answer.
Keyword arguments and attr_accessors are my favorites. Very simple but very powerful.
Being able to make my own version of attr_accessor is awesome.
Memoized attributes are handy.
Treat objects as value objects. fail if this, return if that style is awesome sometimes.
The way boolean operators work so that this_or_that = this || that is possible is awesome. .select(&:this?).map(&:that).reduce(:+) always feels magical. Try that in PHP.
There are a lot of favorites it seems…
Not very favorite:
this || that or ||= doesn’t work when this = false, work around that.
Shared mutable state lurking everywhere (hey, freeze!).
Eval methods are hard to read, so I prefer define-methods instead.