Ruby hash styles formatting
Have you ever felt annoying in formatting of hash keys/values in Ruby code? So have I. And I’m going to describe how to improve it in this post.
Variants of using
Asume we have to write some method build_location which receives hash object with a lot of default parameters. So in this case we have a few variants how to format this peace of code:
- Inline (1)
- Pure blocks (2)
- Using begin-end Pairs (Braces) to Designate Block Boundaries (3)
Block #1 seems disgusting, because we have infinite line of parameters. It is too difficult to find something in it and add new parameter. Block #2 looks rather pretty, but if you want to change parameter name of add one you will have to format them again. So this code is too difficult to support also. So my choose is #3.
The best one
In block #3 we have easy supported code, if we change list of parameters or change name we won’t have to change anything with hash parameters. Code like this I will chose not only for styling method parameters but for any place in code where I have hash with list of many parameters. To confirm this assertion let’s try to change name of parameter and add new:
As you can see I’ve changed only that what I wanted without any regression issues for formatting my code.
A lot of code examples for this theme you can find in book Code Complete, second edition by Steve McConnel. This is a huge book, but it is very interesting, important, and contains a lot of advices for coding. Also it includes in list of books which must read every programmer. Thank you, Steve, for your hard work!
WideFix and Ruby On Rails expertise
At WideFix, we take pride in our expertise and experience. You can trust that our solutions will not harm your business and will always keep your site running smoothly. You can rely on us to provide confident and effective solutions that meet your needs.