在哈希上声明时的ruby情况

时间:2015-05-22 23:14:52

标签: ruby

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

而不是像

那样写作

当“Flat / Unit No.”,“Building No. / Name”,“Street”,“Postcode”,“City / Town”,“Region”,“Suburb”

有没有更好的方法来写这个?

2 个答案:

答案 0 :(得分:0)

就像你已经写过:

MAP_PERSONAL_DATA_WITH_TAG.has_key?(key)

或者只是:

MAP_PERSONAL_DATA_WITH_TAG[key]

或(会慢):

MAP_PERSONAL_DATA_WITH_TAG.keys.include?(key)

答案 1 :(得分:0)

我相信MAP_PERSONAL_DATA_WITH_TAG.has_key?(key)会做的事情。这是使用您提供的信息进行操作的最佳方式。您有一个数据源MAP_PERSONAL_DATA_WITH_TAG和请求哈希 - data_hash。您需要检查每个请求是否在数据源中。

另据我记得,您可以删除puts语句中的所有switch,并将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