3

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
Thillai K
  • 71
  • 12

3 Answers3

10

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).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

You can assign the result of the case statement to a variable directly, like this:

@array1.each do |a1|
  @array2[a1.field_id] = case a1.mapped_field
    when 'value1'
      value_1
    when 'value2'
      value_2
    when 'value3'
      value_3
    when 'value4'
      value_4
    when 'value5'
      value_4
  end
end
Ramses
  • 996
  • 4
  • 12
  • 28
2

You can use then as well

@array1.each do |a1|
  @array2[a1.field_id] = case a1.mapped_field
    when 'value1' then value_1
    when 'value2' then value_2
    when 'value3' then value_3
    when 'value4' then value_4
    when 'value5' then value_5
  end
end
Salil
  • 46,566
  • 21
  • 122
  • 156