Learning Ruby, Day Two

Regular expressions are sort of like in Perl, in that you would write them like this:

if str =~ /Tara|Clark/
  #do something
end

Blocks seem a bit confusing as well. Well I understand the idea of curl braces or do…end distinguishing it from other sections of code, but what confuses me is what they’re used for. The idea of iterators that confused me yesterday makes more sense now, but the idea of associating a block with a method call doesn’t make sense.

Exceptions are caught like this:

begin
  var = try_something_that_could_fail()
rescue CoolException
  STDERR.puts "Useful message " + "I am cool"
rescue Exception => e
  STDERR.puts "Caught Exception with message #{e.message}"
end

irb, or Interactive Ruby, is useful for executing single expressions to see how they work. Try the script/console wrapper.

Predicate methods end with a question mark, like empty? and returns a boolean value.

Bang methods end with an exclamation mark, like empty! which I’m assuming would empty the object.

Like Perl, Ruby has the || operator. So my_var ||= 5 is an excellent way to assign default values since it is equivalent to my_var = my_var || 5, which will keep my_var at its current value if unless it’s false or nil, in which case it will assign 5 to it.

Use self. instead of ClassName. for safety reasons in inheritance setups.

RDoc is like PHPDoc/JavaDoc.

There, I’m now done with the Introduction to Ruby appendix!

This entry was posted in Ruby on Rails and tagged , , , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

One Comment

  1. onitony
    Posted September 15, 2009 at 11:41 pm | Permalink

    Blocks are Closures — http://en.wikipedia.org/wiki/Closure_%28computer_science%29

    Predicate methods indeed return boolean values.

    Bang methods modify the object, while their non-bang counterparts do not.

    irb(main):001:0> foo = "abc123"
    => "abc123"
    irb(main):002:0> foo.gsub(/[a-z]/, '*')
    => "***123"
    irb(main):003:0> foo
    => "abc123"
    irb(main):004:0> foo.gsub!(/[a-z]/, '*')
    => "***123"
    irb(main):005:0> foo
    => "***123"