This is my 3rd day of Ruby in the Seven Languages in Seven Weeks series of posts. You can find the previous day here.
Ruby, Day 3: Thoughts
The third day combines metaprogramming techniques (define_method, method_missing, and mixins) with what what we learned in the previous chapters (flexible syntax, blocks, yield) to work some magic. Whereas day 1 and 2 showed how Ruby could be more concise and expressive than other languages, this chapter shows some of the capabilities available in Ruby, such as beautiful DSLs and composable designs, that are nearly impossible in stricter languages.
I saw small of examples of this when I was working on the Resume Builder: the profile data I was fetching from the LinkedIn APIs came back as JSON. I wanted to have a nice Ruby class to wrap the JSON data and was able to do this cleanly and concisely using some very simple metaprogramming:
Instead of defining dozens of getters and setters as in the LinkedIn API Java
Library,
I just declared the fields in an array (SIMPLE_PROFILE_FIELDS
), looped over
them, and used define_method to create the appropriate methods. To be fair,
this is kids stuff; if you really want to see metaprogramming shine, take a
gander over at
ActiveRecord.
Of course, with great power comes great big bullet wounds in the foot. Metaprogramming must be used with more a bit more caution than other programming techniques, as chasing down errors in dynamic methods and trying to discern “magic” can be painful.
Ruby, Day 3: Problems
CSV application
There was only one problem to solve on this day: modify the CSV application
(see Ruby, Day 2)
to return a CsvRow
object. Use method_missing
on that CsvRow
to return the value
for the column given a heading.
Using this sample file:
The code above will produce the following output:
Moving on
This was the final day in the Ruby chapter. Join me next time as I work my way through a totally new language: Io.
Yevgeniy Brikman
If you enjoyed this post, you may also like my books, Hello, Startup and Terraform: Up & Running. If you need help with DevOps or infrastructure, reach out to me at Gruntwork.