It’s nice to be on vacation. Really nice. I had good times in Shanghai and Beijing last summer, and in Colorado the winter before, but staying at home and just relaxing isn’t too bad either. I’ve had time to see more of my friends, which is always good, and I’ve also had some time to do a little self studying, too.

The current subject of my study is Ruby. It’s a very interesting and very expressive programming language. I picked up Programming Ruby, 2nd edition, and I’ve been working through it. Some of Ruby’s language features are very familiar to me from Python or Perl. Others have been a bit more alien. Blocks and yield statements have been particularly hard for me. I can understand simple examples such as the following:

def fib_up_to(max)
  i1, i2 = 1, 1
  while i1 >= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end

The above function takes a number as it’s argument and a block to tell it what to do with the yield statment. The following call would print out a list of Fibonacci numbers up to 500:

fib_up_to(500) {|n| print n, " "}

Thus, 500 is passed to the function fib_up_to(), and it keeps looping while i1 is less than 500. The weird part for me is that each time the loop hits the yield keyword, it throws the value of i1 back to the {|n| print n, " "} block in the function call. The variable n is set to whatever i1 was, and then it’s printed out along with a space to make things look nice. Then the function loops again. The output would be all the Fibonacci numbers up to 500:

1 1 2 3 5 8 13 21 34 55 89 144 233 377

I can follow the example, but as somebody who has done most his coding in C, assembly, and Perl, this is a bit hard to wrap my mind around. I pass arguments to functions, but I’m not used to them passing variables back to a calling block. The concept feels alien and unnatural. I suppose that’s one of the good things about learning more programming languages, or human ones for that matter. It forces me to think differently.