I spent the last few days going through the Ruby Koans I mentioned in my previous post, and I stand by my initial opinion that it’s easily the best and quickest way to get into the language. I had too much fun doing them, and know much more Ruby than when I began.
The best part is that this knowledge is bound to stick longer than anything I’ve ever read about it before, simply because I was learning through practice (fun!) rather than reading (boring!).
Here is my solution to the last of the more complex puzzles in the set. I’m only posting this one as it’s the only one of the “project” Koans I did completely by myself. The others were done with some assistance from the Google knowledge base.
# about_proxy_object_project.rb
class Proxy
attr_accessor :messages
def initialize(target_object)
@object = target_object
@messages = []
end
def method_missing(method_name, *args, &block)
@messages << method_name
@object.send(method_name, *args, &block)
end
def called?(method_name)
@messages.include? method_name
end
def number_of_times_called(method_name)
@messages.select {|meth| meth =~ /#{method_name.to_s.sub(/\?/, '\?')}.size
end
end
I knew line 20 was ugly (nested regexps… :-S) and that there had to be a cleaner way. Sure enough, I found this, which is pretty much what I had, only without the brain fart of using the match method. :-/
Some minor criticism for the Koans:
- I feel blocks should’ve been dealt with more thoroughly. They’re one of the most distinguishing aspects of Ruby, that is often challenging for beginners. Strings and classes got a deservedly broad explanation, but I think blocks should have been given more attention, because of their importance and broad usage.
- There’s a small bug with Ruby 1.9 in about_strings.rb (method test_single_characters_are_represented_by_integers). The ?<char> syntax for finding the ASCII code was removed in 1.9 and <char>.ord must be used instead. Meaning ‘a’.ord and not ?a. Not a big deal, and it’s a quick fix, but it threw me off for a few minutes. Serves me right for not using the standard 1.8 version.
All in all, I’m very happy with my results. I know I’ll be going back to the solutions for reference in the future, and the learning process was invaluable for me.
Although I’m still awfully green with the language, I feel like I have enough base to begin tackling AWDR. As a sidenote, I’ve decided it’s best for me to learn Rails first, instead of the framework du jour (which might or might not be “better”), simply because it’s the single most popular Ruby project. Having used a few MVC web frameworks in the past, I might feel more at home than with others that don’t necessarily force the paradigm. I think that when I get some experience with RoR, I’ll know enough Ruby to explore other options and see what I like best.
2010 will be a great year! ![]()