Category: Computing

December 17th, 2013

“Autovivifying” Ruby Hashes (another code nugget)

I often found Perl’s “autovivification” of intermediate levels of a nested hash useful, particularly in quick and dirty scripts were defining a real object and access methods seemed like overkill.

Recently I noticed a post on the ruby-lang mailing list from Jesús Gabriel y Galán which showed a technique which approximates the autovivifacation in Ruby.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ratdog:~ mike$ pry --simple-prompt
>> hash = Hash.new { |h, k| h[k] = Hash.new &h.default_proc }
=> {}
>> hash[:foo][:bar][:baz] = 'plugh'; hash
=> {
    :foo => {
        :bar => {
            :baz => "plugh"
        }
    }
}
>> hash[:foo][:baa][:bax] = 'oops'; hash
=> {
    :foo => {
        :bar => {
            :baz => "plugh"
        },
        :baa => {
            :bax => "oops"
        }
    }
}

There is a difference in behaviour between Perl and Ruby when an attempt to read a non-existent element is made. In Ruby the access will create the element as a new empty hash:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>hash[:a][:b][:c]
=> {}
>> hash
=> {
    :foo => {
        :bar => {
            :baz => "plugh"
        },
        :baa => {
            :bax => "oops"
        }
    },
      :a => {
        :b => {
            :c => {}
        }
    }
}
>>

It’s still a good trick for my Ruby toolbox, and a good reminder to refresh my memory on the less frequently used methods on Hash.

November 25th, 2013

Code Nugget of the Day

The Ruby language mailing list is often a source of gentle reminders about things I might have missed, and I read Robert Klemme’s with particular interest. One of his recent posts was a nice reminder of a way to initialise an array without using map, which is where I usually end up when I don’t think:

1
2
3
ratdog:~ mike$ pry --simple-prompt
>> odds = (0 .. 9).map { |i| i * 2 + 1 }
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Ruby’s core documentation for Array.new mentions the form Array.new(size) {|index| block }, so we can do something like:

4
5
>> odds = Array.new(10) { |i| i * 2 + 1 }
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

I could use an Enumerator to generate a list of odd numbers, and take the first ten:

6
7
8
9
>> odd_gen = Enumerator.new { |y| n = 0 ; loop { y.yield n * 2 + 1; n += 1 } }
=> #<Enumerator: ...>
>> odd_gen.take 10
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Hmmm… maybe this is not a good case for Enumerator — it’s always good to go for simple where possible!

November 8th, 2013

Rediscovering Interests

One of my favourite courses in Computing at university was compiler writing, and nearly three decades after taking it I am still in touch with the person who taught the course. That course fuelled my interest in programming languages, which has survived the decades reasonably intact.

Recently I picked up Tom Stuart’s Understanding Computation book, and I’m working trough it with a pry window open alongside the electronic book. It takes me back a bit, and makes me realize how much I’ve forgotten. If you’re interested then he did an interview on the Ruby Rogues podcast recently, and it is entertaining and enlightening listen.

If I tell the truth, I bought the book a while ago with the intent of reading it before the Ruby Rogues episode. Good intentions, good intentions…

One of the parts of the Ruby Rogues episode which most interested me was Tom’s explanation of why he used Ruby. I found it interesting because I haven’t been able to express why I like using Ruby as well as he does:

I did start doing it with Ruby because that was the language I wanted to do it in, but I was definitely open to the idea of I might get halfway through this book and realize it would be much better to do it in JavaScript or to do it in a language like standardml for example, which has got much better support for functional programming and pattern matching and a load of features that I wish I had to be able to explain stuff, or doing it all in Lisp and then maybe the stuff about syntax I wouldn’t have to say so much because I could just represent everything with S-expressions. I was definitely on the fence about whether Ruby was the right thing. But then the more I got into it and the more of it I wrote, the more I felt like, in a way that I can’t quite put my finger on, it felt like Ruby was being strangely cooperative.

The notion of a program as like a roiling pop of collaborating objects that are all just sending messages to each other and being able to go in and modify the method tables of those objects and put new implementations of methods into them whenever I wanted to meant that I could do this slightly weird thing where we’re walking through a chapter and it’s really just an annotated IRB session where I’m just, “Now if you paste this in on the console then all of your objects have this new method and you can actually call that method on those objects.” It felt like a natural way of explaining stuff and I was really happy with that because it helped me solidify some of the things that I really enjoy about Ruby. And actually, since writing the book I feel more enthusiastic about Ruby now.

I’m a few pages into the book and I’m glad I bought it!

September 1st, 2013

Some Lessons Learned from Pair Programming (Part 1)

There are many simple ways improve my programming!

That was the biggest thing I have learned from my pair programming efforts so far. The more useful things I need to pay attention to:

  • Be more careful with my git commits — I can learn to rebase before committing so my commits tell a coherent story.
  • Listen to my gut more — Several things I felt “iffy” about also concerned my partner. I should speak up more during coding rather than skate over things, for example names I think are not quite right.
  • Pairing up takes energy and focus — It’s rewarding too. I have to have mental energy and focus, otherwise I’m wasting my partner’s time if I am not participating fully.

The incidental benefits were great too. We explored more options than I would have done by myself. We learned about more than just the problem we were solving. It was good to have someone to celebrate the successes with, as well as another pair of eyes to give a better perspective on the things which didn’t work out.

So far pairing seems to have amply rewarded my investment in time.

August 31st, 2013

Adventures in Pair Programming (Part 5)

At the August Toronto Perl Mongers meeting I gave a “brief” presentation of my experiences of pair programming. Fortunately some of my pair mates were in the audience, as were some Perl programmers with challenging questions, and they improved the presentation’s value to me.

As I have yet to succeed at getting pairing accepted at #{work}, I had become pretty despondent about ever getting to do any pair programming. Luckily for me, Avdi Grimm started publicising http://pairprogramwith.me and I reasoned that if I cared about trying pairing seriously I might as well do it for myself, and the past few weeks have been enlightening.

Doing the presentation the the Perl programmers this month served as a useful retrospective. Some of the points raised were:

  • Enhanced discipline — As an example: both pair members admitted that it was hard to stick to TDD individually, but when in a pair it was possible and seen to be beneficial.
  • Willingness to try different approaches — If we had a couple of different ideas it was easier in a pair situation to try them all, and learn from those which didn’t work out so well as well as those which seemed to work.
  • The code, and any metaphors being used were discussed — this improved all kinds of things: code complexity, naming of things, conceptual coherence, and more.
  • Time management (pomodoro) led to frequent “mini-retrospectives” — this was unexpected. When the timer went off it seemed natural to discuss what had just happened in a broader context, reflecting on the way we were working rather than what we were doing.
  • Time management helped us remember to switch roles — This made sure one person didn’t accidentally hog the keyboard by making sure we tracked time and were interrupted.

There were some good skeptical questions asked too, about pair programming and extreme programming. Their essences included:

  • Isn’t this just a fad?
  • What if my personality type isn’t suited to pair programming?
  • Isn’t relying on communication flowing through a chain of pairing sessions dangerously like a game of Chinese whispers?
  • Didn’t the project where XP emerged end in failure?
  • Don’t we still need comprehensive and accurate documentation of some elements of a project to be developed?

I had a great time presenting it, and appreciated the audience participation. Some of the questions made me look at my assumptions and prejudices.

A PDF copy of my slides is available here: TPM Adventures in Pair Programming 2013 08 29. There are some links in there which are good starting points for exploration.

August 24th, 2013

Adventures in Pair Programming (Part 4)

Another beautiful Saturday in Toronto, and another chance to do a good couple of sessions with Stuart Watt. This week there was a good mixture of programming in Ruby (a language I know and love), programming in Elixir (a language which has piqued my interest), exploring a few tools, and reviewing my presentation for the Toronto Perl Mongers‘ meeting this Thursday.

The Ruby was just a few odds and ends, renaming, refactoring dense methods, and doing things I probably would never have done had I been working alone. I was also helped by 8th Color‘s reviewing service — though that meant I pushed to the branch way too often just to see what would happen. All in all it was a good experience, knowing my partner would be checking that I had made the changes as agreed made me more careful. These changes were to code I wrote solo after last week’s session — they probably wouldn’t have been needed if we were pairing when I was writing the code.

The Elixir was a case of starting to pick things up — Stuart has some functional experience so he was able to point me in a reasonable direction. Here pairing was doing knowledge transfer and helping avoid rat-holes. It seemed important to step away from time to time and chat about other things in the world to let my subconscious process what I was doing.

The tool I experimented with today was Atlassian‘s SourceTree which is a graphical git (and mercurial) client with built in support for git flow. Seems nice, although I couldn’t find a way to get nice diffs for all the files in a commit in one pane — but I can use github for that.

Having a partner look over my presentation was useful, I think the presentation will be better for it!

Best of all we headed out to Merryberry for some lunch. The food is always great there, and it was a beautiful day to walk out past Riverdale Farm to get some lunch.

August 17th, 2013

Adventures in Pair Programming (Part 3)

Time is passing, and my pair programming presentation at the Toronto Perl Mongers is looming. So it’s time to do some more preparation…

Today I had a friend over to try some pair programming. I wanted to attack a simple problem so we could focus on the mechanics of pair programming without being too distracted by the problem itself. Some of the things I wanted to try included:

  • One keyboard / screen / mouse.
  • Pomodoro time management so we made sure we swapped rôles.
  • A real attempt to do Test Driven Design, where we let the error messages guide us and didn’t let the temptation to code wildly seduce us.
  • A real attempt at the red / green / refactor cycle, so we could make it work and then make it right.

The experience was positive. Very positive! As I work as part of a dispersed team it was a delight for coding to become a fun, social activity.

I didn’t quite succeed at the one keyboard / screen / mouse — we used a laptop with an external display, and a USB keyboard and mouse. For most of the time we were doing pair programming, and occasionally the “non-driver” would use the other keyboard to look something up. For the bulk of the time both of our attention was on the shared screen.

The Pomodoro time management worked well, a chance to get up and walk around, get away from the computer and let our subconscious minds kick in worked. We used the interruption to change rôles, and we were pretty good at stopping when the timer went off — if a test was failing then it would remind us where to pick up (particularly after lunch at the House on Parliament).

TDD worked well, we did discuss things a couple of steps into the future and yet managed to focus on failing tests and doing one step at a time. This lead to discussions about possible ways to continue and every error seemed to open up possibilities rather than be a blocker. It was reassuring to do things in small steps because we were never far from a working state. Several names got changed as we discussed what was being written, and saw how the tests communicated (or failed to communicate) the intent of the code we were testing.

The red / green / refactor cycle was useful because it reduced distraction. We could make it work and then rearrange code in the refactor phase. This was the first time I had had a partner to do refactoring with, and the discussions about where stuff belonged and what it should be called were fun and useful.

There were other benefits too. We shared information about tools which we had used, when I couldn’t explain Ruby namespacing then I realised I had to do some learning myself. “Failing” in this environment was a learning opportunity.

In conclusion… What a great day. Good research for my talk, good progress on a project, and a very satisfying day. Thanks to Stuart Watt, my partner in pairing!


Background: The problem is how to iterate over an IO stream which contains a tar file in an idiomatic Ruby way. This will fix a problem at #{work}, but I’d like to enjoy it so I’ll do it on my own time. If you care, the work is on GitHub.

August 2nd, 2013

Adventures in Pair Programming (Part 2)

A few days ago I had my first remote pair programming experience which got some real work done. Dave Doyle had set up the Toronto Perl Mongers meetup group, and we thought it might be good to deal with at least one issue with our web site.

One tool which I first heard about on the Wide Teams podcast was Screenhero. I had had a couple of opportunities to use it at work for code reviewing, and this was the first time I was going to try real development.

Using Screenhero was a real pleasure, the fans on my MacBook Pro sometimes leaped into high gear, but the performance of sharing multiple windows in both directions while having a Skype video chat running was never a problem. There were a few times when the remoteness of the other machine intruded, but it was a very natural feeling experience. We could talk and gesture with our mouses (micen?), roll our eyes or give thumbs-up, and Screenhero didn’t get in the way of solving the problem. We tried a few things, explored some dead-ends, and came to a conclusion quite easily.

Definitely a positive experience.

July 28th, 2013

No Adventures in Pair Programming (yet…)

Both pair programming partners have yet to pair with me. I have learned a few things getting my infrastructure set up, and I’m getting impatient to try it!

July 20th, 2013

Adventures in Pair Programming (Part 1)

Recent lifestyle changes have left me with more energy and desire to learn, so I am looking into doing some remote pairing with some friends in the city. I expect that working with people I already have a relationship with will help get the kinks out of my setup, and then I can look to people further afield.

One thing I think I’ll miss is the food and beer afterwards, but that might be an advantage from the perspective of my wife and my doctor!

The current plan is to get a droplet or two at Digital Ocean – they have SSDs and per hour pricing – and maybe do some pairing as I work through Michael Hartl‘s Rails tutorial.

This has a couple of benefits for me:

  • My progress on the Rails tutorial is open to others, and that helps keep me honest
  • I have an excuse to start exploring Vagrant and Puppet in my own world as ways to build and provision machines

For now I have some simple scripts at https://github.com/mikestok/pairing-vps which I use to build a VPS. There are lots of routes open to improve them, and I want to get the pair programming experience first before burning hours on perfecting a useless system.