I’ve recently spotted a curious trend in blogposts about Ruby. It’s the way people define classes in examples. It goes like this:
Why? Because it’s shorter replacement for this:
The other way to save typing on attributes lookes like this:
It brought up an interesting discussion on twitter, when @jeg2 said he didn’t like the practice. One important consequence of using it that was mentioned in this discussion is changing of ancestor chain.
When declaring class usual way:
When inheriting from Struct.new
:
When creating a constant from Struct.new
:
Have you noticed Enumerable
in two later cases? It means that suddenly instances of your class start to respond to each
method and a bunch of other methods. So it’s better be careful using Struct
like this.