Aspyct.org

Ruby, a beginner's overview

| Comments

Ruby has been lying around for a while now, and I did not take the time to discover it yet… Since I installed Octopress, I’ve been looking more and more into the source files of this system. Am I falling for ruby? Don’t know, but it definitely looks like a very interesting language!

The first thing I stumbled upon was the :symbol notation. To me, it sounds like a kind of enum without enum, or constants without constants. Just values, that you can match in if statements or probably dictionaries.

1
2
3
4
p = Post.new
p.state = :draft
p.state = :published
p.state = :deleted

There is also the familiar (if you’ve played with python before) raise to signal an error, and the… throw/catch? So which one should I use for my exceptions? Turns out the throw is not what I expected. It’s more like a superfast return, “throw a ball and catch it”.

1
2
3
4
5
6
7
8
9
10
11
12
13
def solve(problem)
  catch (:solution) {
      backtrack_solve(problem)
  }
end

def backtrack_solve(problem)
  if problem.solved
      throw :solution, current_solution
  else
      # Do complicated recursion stuff
  end
end

(Oh, and did you see it? There is an implicit return from the function solve ;)

Ruby seems to borrow some language constructs from perl. For example, the well-known print x unless y and the like.

1
puts "bananas!" unless monkey

More interestingly, ruby also has regex integrated to the language, which is something I really miss in most languages out there. Note also the string interpolation thanks to #{$var} (which is pretty hard to type on my keyboard, by the way…)

1
2
3
if "spam & eggs" =~ /egg(s?)/
  puts "We found egg#{$1}"
end

Procs & blocks are, to me, one of the most interesting part of ruby. Basically, they’re just lambda functions. But their syntax is very clean and nicely integrated with ruby overall. The following code is actually what decided me to learn more about ruby:

1
2
3
task :new_post, :title do |t, args|
  # Random code
end

This is an extract of the Rakefile found in Octopress. So what can we see here? Of course, task is not a ruby-defined construct or function. It’s actually a function provided by Rake, that takes, at least, two arguments (can someone tell me why there is exactly 1 comma ‘,’ in this function call ?)

The last argument of this function is what we call a block, and can be defined either as do |args| ... end or { |args| ... }. This block can later be turned into a so-called “proc” and be executed by other methods, just like a lambda function.

There’s a lot more to say about ruby. I could talk about frozen objects, domain specific languages, classes and a few surprising methods I discovered by chance while writing this article. There’s probably even more I have yet to discover…

1
2
3
so do |you|
  you.tell :me "what else is awesome in ruby?"
end # and thanks for reading ;)

Comments