Rails Learning On the Fly
When you're learning a programming language out of necessity, you skip some steps along the way in order to accomplish the immediate goals you're focused on. Going back and finding those missed steps is important once you get to a point where you're comfortable executing your daily tasks without reference. So here are some Ruby on Rails pieces of code I learned after the fact.
Manipulating data sets in Rails is made simple by two simple symbols - ampersand (&) and bar (|). & takes two data sets and returns the common objects in the set. Bar (|) returns all items in both sets but only unique items. Simple tools for your Rails toolbox and if you missed them in the beginning of your learning, like me, they can become very handy when thinking through solutions.
If you're a C++ or PHP guy, this next one is great. Collect is a method on array that is extremely useful when you want to access a particular attribute on an object in one line of code. Example 1 illustrates a lengthy alternative to accomplish what the collect method does.
Both of these next blocks execute the same query, but one is much cleaner than the other. It may be somewhat subtle, but the difference can do a lot in terms of code readability and consistency. There's also a hidden gem in there - :historical_ID => pkg_arr where pkg_arr is an array of ideas. This is the same as "historical_id IN (3234, 2349, 23434)". Very useful for big sets.
Last one is simple. How to build a quick array for iterating purposes. Both examples achieve the same goal, but one in less than half the code.
I know these aren't revelations in the code world, but every ounce of productivity matters and if one of these can save you a couple lines of code, well then it's worth it.
Dan
Front-End Developer and Ruby on Rails Newbie
dan@thredup.com