Search code examples
ruby-on-railsarraysrubyswitch-statementcase-statement

Alternative for case when statement in ruby


I am assigning a set of values based on the values of a hash.

I have to assign values to another hash key based on the value of the incoming hash key.

There are more than 10 keys in the incoming hash(so more than 10 cases).

I want to minimize the code. Is there any alternative method for this scenario to shorten the code.

@hash1.each do |h1|
  case h1.mapped_field
    when 'value1'
      @hash2[h1.field_id] = value_1
    when 'value2'
      @hash2[h1.field_id] = value_2
    when 'value3'
      @hash2[h1.field_id] = value_3
    when 'value4'
      @hash2[h1.field_id] = value_4
    when 'value5'
      @hash2[h1.field_id] = value_5
  end
end

Solution

  • Here's another alternative: not using the case/when at all.

    mapping = {
      'value1' => value_1,
      'value2' => value_2,
      ...
    }
    
    @array1.each do |a1|
      @array2[a1.field_id] = mapping[a1.mapped_field]
    end
    

    As a pleasant bonus, you now can build the mapping programmatically (by loading it from a file/database or something like that).