Writing more readable ruby code
Best thing about ruby, is that it’s clean. You feel more writing english than writing code. Sadly I didn't realize this before, and if you are new to ruby and rails. You're probably writing code like this …
It might look normal to you because you're used to it by now, but it has adds overhead when reading. You have to read every line translate it, keep variables flow in mind, and remember what each function does. And if you have like 20 lines, that would be even more pain in the ass.
Instead why not write instructions directly. Why not say what you want to say in plain english.
This doesn't eliminate the coding part. It just gets it deferred to private methods. When reading public methods, you don’t care about the flow of variables or which method gets called, you only care about the big picture.
This helps by making public methods scannable, something that you can read. Something you don't have to compile in your mind.
It makes your code DRY, and constructed of small single tasked reusable methods.
To wrap up
- Move all class calls and assignments into small private methods, each responsible for one small task.
- Write more descriptive method names, it’s ok to have long names, but not very long. Take your time thinking about it, and make sure that it’s clear what the method does. e.x. authenticate_using_email, sorty_by_popularity, filter_by_author, …etc.
- Prefer use of instance variables (@variable) for global assignments over passing parameters, and assigning them back to another variable.
- Optional: Use rubocop to help you follow Ruby style guidelines.
Do you have a better way or tips on enhancing this? would love to hear your thoughts
If you find this helpful, don't forget to hit Recommend button
Published by: Seif in Development