The third day combines
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
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
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
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:
This was the final day in the Ruby chapter. Join me next time as I work my way
through a totally new language: Io.