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'


  when 'short'


  when 'buy_contract'


  when 'short_contract'




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


  'buy'            => 'sell',

  'short'          => 'cover',

  'buy_contract'   => 'sell_contract',

  'short_contract' => 'cover_contract'


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

>> require 'benchmark'


>> do |x|'hash') { 10_000_000.times { REALIZING_TRADE_TYPES['buy'] } }'case-statement') { 10_000_000.times { realizing_trade_type 'buy' } }'empty') { 10_000_000.times {} }


                      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.

Do you have a project for us?Get a free quote