Ruby Hash coolness September 28th, 2009

Don’t shoot me if you already use this every day, but this is new to me.

In the past I’ve often had code like this

@hosts = {}

@accounts.each do |account|
  @hosts[account[:host]] ||= []
  @hosts[account[:host]] << account
end

But why do this hen you can just add some initializer code to your hash.

@hosts = Hash.new { |h, k| h[k] = [] }

@accounts.each do |account|
  @hosts[account[:host]] << account
end

Where Hash automatically invokes the block when an unknown hash key is called. Great!

tags: l 76 comments »

small less-tip December 3rd, 2008

When you’re using less to view your Rails log, and you want your colours back, you can use less with the -R option, or you can automate this by setting the $LESS variable in your environment. So for a bash environment:

# ~/.profile
export LESS="-R"

Update!

Since setting $LESS in your environment affects git commands like status (git status automatically uses less) I updated by profile a bit:

# ~/.profile
# Disabled: Fucks up git status
# export LESS="-R"
alias less="less -R"
tags: l 2 comments »