Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

Use hash or case-statement in Ruby?

Often, when we need to get a value based on the other one, we’re using a case-statement. Like this

def realizing_trade_type(realizable_trade_type)
  case realizable_trade_type
  when 'buy'
    'sell'
  when 'short'
    'cover'
  when 'buy_contract'
    'sell_contract'
  when 'short_contract'
    'cover_contract'
  end
end

But, if the conditions and the results are simple values, why don’t we use hash for this? We can :)

REALIZING_TRADE_TYPES = {
  'buy'            => 'sell',
  'short'          => 'cover',
  'buy_contract'   => 'sell_contract',
  'short_contract' => 'cover_contract'
}.freeze

Here is the benchmark of both options, executed 10_000_000 times. It shows that a hash is faster in times for such the kind of usage.

>> require 'benchmark'
true
>> Benchmark.bm(15) do |x|
  x.report('hash') { 10_000_000.times { REALIZING_TRADE_TYPES['buy'] } }
  x.report('case-statement') { 10_000_000.times { realizing_trade_type 'buy' } }
  x.report('empty') { 10_000_000.times {} }
end
                      user     system      total        real
hash              0.990423   0.003412   0.993835 (  1.057612)
case-statement    1.752263   0.004531   1.756794 (  1.762030)
empty             0.380810   0.000728   0.381538 (  0.382153)

So, it’s better to use a hash when you are just retrieving some values (like in the example above). If there is additional logic to execute, a case-statement is still a way to go.

Looking for help? Each developer at JetRockets has years of experience working with Ruby applications of all types and sizes. Contact us and find out how we can help you.