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

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:

  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}"

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!


One Response to “Learning Ruby, Day Two”

  1. 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"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: