Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby case when语句在哈希上_Ruby - Fatal编程技术网

ruby case when语句在哈希上

ruby case when语句在哈希上,ruby,Ruby,而不是像这样写 当单位/单元号、建筑号/名称、街道、邮政编码、城市/城镇、地区、郊区 有没有更好的方法写这篇文章?就像你已经写的那样: MAP_PERSONAL_DATA_WITH_TAG = {"Flat/Unit No." => "FLD_ADD_1Line1", "Building No./Name" => "FLD_ADD_2Line2", "Street" => "

而不是像这样写

当单位/单元号、建筑号/名称、街道、邮政编码、城市/城镇、地区、郊区


有没有更好的方法写这篇文章?

就像你已经写的那样:

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
或者只是:

MAP_PERSONAL_DATA_WITH_TAG.has_key?(key)
或者更慢一些:

MAP_PERSONAL_DATA_WITH_TAG[key]
我相信带标签的地图、个人资料、钥匙会起作用。这是用你提供的信息来做这件事的最好方法。您有一个数据源映射\u PERSONAL\u data\u,带有\u标记和请求hash-data\u hash。您需要检查数据源中的每个请求

我还记得,您可以删除switch语句中的所有put,并将put放在case之前

但还有一种方法。在陈述时留下一个案例。所以这可能更优雅

MAP_PERSONAL_DATA_WITH_TAG.keys.include?(key)

如果我将选项用作case..when的一部分,它似乎不起作用。实际上,我只需要使用case when语句,因为在上面的示例中没有提到的MAP_PERSONAL_DATA_WITH_TAG等其他散列中还有一些选项。我需要对DATA_散列中的所有键执行“put”语句
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