2015-05-22 63 views
0
MAP_PERSONAL_DATA_WITH_TAG = {"Flat/Unit No." => "FLD_ADD_1Line1", 
          "Building No./Name" => "FLD_ADD_2Line2", 
          "Street" => "FLD_ADD_3Line3", 
          "Postcode" => "FLD_ADD_4Postcode", 
          "City/Town" => "FLD_ADD_5City", 
          "Region" => "FLD_ADD_6State", 
          "Suburb" => "FLD_ADD_Town" 
} 

data_hash = {"Street" => "s", "Suburb" => "sb", "abc" => "hdkhd"} 

data_hash.each do |key, value| 
    case key 
    when <if key equal to the key of MAP_PERSONAL_DATA_WITH_TAG i.e MAP_PERSONAL_DATA_WITH_TAG.has_key?(key)> 
    puts 'something' 
    when "Mobile" 
    puts "something mobile" 
    else 
    puts 'something else' 
    end 
end 

不用編寫像紅寶石情況下,當一個散列聲明

當「平/無單位」,「建設No./Name","Street","Postcode","City/Town 「,」地區「,」郊區「

有沒有更好的方法來寫這個?

+0

我需要對data_hash – asinha

回答

0

像你已經寫道:

MAP_PERSONAL_DATA_WITH_TAG.has_key?(key) 

或者只是:

MAP_PERSONAL_DATA_WITH_TAG[key] 

或(將變得更慢):

MAP_PERSONAL_DATA_WITH_TAG.keys.include?(key) 
+0

中的所有鍵執行'put'語句,它似乎不起作用。我檢查了irb。 – asinha

0

相信MAP_PERSONAL_DATA_WITH_TAG.has_key?(key)會做的事。這是用你提供的信息來完成的最好方法。你有一個數據源MAP_PERSONAL_DATA_WITH_TAG和請求散列 - data_hash。您需要檢查每個請求是否在數據源中。

也正如我記得你可以刪除switch聲明中的所有puts,並把puts之前的情況。

但還有一種方法。離開case-when聲明。所以這可能更優雅。

data_hash.each do |key, value| 
    # Check if the key is Mobile (this is non-trivial key) 
    puts "something mobile" if key == "Mobile" 

    # Simply check if there is data in the hash for the key 
    # if yes - the result will be a string and will eveluate to true 
    # causing the first string to be printed out. But if there is no 
    # other such key in the hash - you will get nil that will be 
    # evaluated to false resulting in the second string to be returned 
    # from expression in curly braces and sequentally to be printed. 
    puts (MAP_PERSONAL_DATA_WITH_TAG[key] ? 'something' : 'something else') 
end 
+0

如果我使用該選項作爲case的一部分,那麼它似乎不起作用。實際上我只需要使用case語句,因爲除了上面例子中沒有提到的MAP_PERSONAL_DATA_WITH_TAG之外,其他幾個哈希函數還有其他幾個選項。 – asinha