簡體   English   中英

在ruby中聲明的情況的替代方案

[英]Alternative for case when statement in ruby

我正在根據哈希值分配一組值。

我必須根據傳入的哈希鍵的值為另一個哈希鍵分配值。

傳入哈希中有超過10個鍵(因此超過10個案例)。

我想最小化代碼。 是否有任何替代方法可以縮短代碼。

@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

這是另一種選擇:不使用案例/何時使用。

mapping = {
  'value1' => value_1,
  'value2' => value_2,
  ...
}

@array1.each do |a1|
  @array2[a1.field_id] = mapping[a1.mapped_field]
end

作為一個令人愉快的獎勵,您現在可以以編程方式構建映射(通過從文件/數據庫或類似的東西加載它)。

您可以直接將case語句的結果分配給變量,如下所示:

@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

您可以使用then還有

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM