Ruby Hash Tricks

Some really cool tricks with Ruby hashes–if you supply a block to Hash.new, that will act as a default value for a given key. For example, here’s a Fibonacci hash I put together which caches the values (making it pretty quick):

fibonacci = Hash.new do |h,k|
  if k < 2
    h[k] = k
  else
    h[k] = h[k-1] + h[k-2]
  end
end

fibonacci[6]   # => 8
fibonacci[100] # => 354224848179261915075

Reblogged from: RailsTips
Posted on December 27, 2010
Tagged with: , ,

Leave A Comment

Ajax-loader