While looking at some bits of other peoples Ruby code I came across a few shortcuts and interesting structures worth mentioning.
Exception handling shortcut
First up a shortcut to catch exceptions thrown by a method:
def say_foo puts "foo" if doit rescue Exception puts "#fail" end |
So since we didn’t define doit this will raise an exception, which will be handled. Nice shortcut to avoid an extra inner begin / rescue block.
sprintf equivelant
Ruby supports sprintf style string building in a handy little shortcut:
puts "%2.6f\n%d" % [1, 1] |
This produces:
$ ruby test.rb 1.000000 1 |
Get a value from a hash with default for non existing
This is really nice, I’ve written way too many constructs like this:
foo.include?(:bar) ? bar = foo[:bar] : bar = "unknown" |
One option that I was told about was this:
bar = foo[:bar] || "unknown" |
But that does not work if you had false in the hash, or maybe even nil.
Turns out there’s an awesome shortcut for this:
bar = foo.fetch(:bar, "unknown") |
Reloading a class
Sometimes you want to reload a class you previously loaded with require. I have the need in my plugin manager for mcollective. There’s a simple fix by simply using Kernel#load to load the .rb file, each time you load it the file will be reloaded from disk.
irb(main):001:0> load "test.rb" => true irb(main):002:0> Foo.doit foo irb(main):003:0* load "test.rb" => true irb(main):004:0> Foo.doit foo foo |
In between lines 2 and 3 I edited the file test.rb and just reloaded it, the changes on disk reflected in the current session. The main difference is that you need to supply the full file name and not just test like you would with require.