更新ruby中的哈希段

时间:2015-07-03 20:27:54

标签: ruby

我有这样的哈希:

string GetListBoxSelections(CheckBoxList cb)
    {
        string rv = string.Empty;
        // Iterate through the Items collection of the CheckBoxList 
        // control and build a string of the selected items.
        string c = cbContactTypes.Items.Count.ToString();

        for (int i = 0; i < cb.Items.Count; i++)
        {
            if (cb.Items[i].Selected)
            {
                // here i need to build a string...
                // for example if check box list items 2,5 & 8 are selected then
                // i need to buld a string equal to "2,5,8"
                // this enables will enable me to bulk insert or update contact types 
                // and interfaces per contact with the Support.Contact_Save stoed procedure
                string Separator = rv.Length > 0 ? "," : "";
                rv += Separator + cb.Items[i].Value.ToString();
            }

        }
        return rv;
    }

在上面的哈希中,布尔值是字符串。我希望他们是布尔人。也有可能 许多键/值对但值始终为“true”或“false”。这是我的解决方案:

fields = {
  '0' => {
    'field' => 'something',
    'field_type' => 'something type',
    'validation' => { 'enabled' => 'true', 'persisted' => 'false', 'another thing' => 'false' }
  },
  '1' => {
    'field' => 'something else',
    'field_type' => 'something else type',
    'validation' => { 'enabled' => 'true', 'persisted' => 'false' }
  }
}

它有效,但我的预感是它很慢而且有错误。有没有更有效的方法来实现这一点,也许内联(不创建副本)?

3 个答案:

答案 0 :(得分:0)

这将修改内联哈希:

fields.each do |record, data|
  data.each do |field, value|
    next unless value.is_a?(Hash)
    value.each do |subkey, subvalue|
      fields[record][field][subkey] = subvalue == 'true'
    end
  end
end

基本上,只需循环遍历每个哈希,但将密钥存储在每个嵌套级别,这样您就可以直接在最里面的循环中分配值。

答案 1 :(得分:0)

这是一个可以处理 任何哈希结构 的解决方案,无论哈希是什么样的:

def convert_boolstring_to_boolean(hash)
  return if hash.class != Hash
  hash.each_pair do |k, v|
    convert_boolstring_to_boolean(hash[k]) if v.class == Hash
    hash[k] = (v == "true") if ["true", "false"].include?(v)
  end
end

convert_boolstring_to_boolean(fields)

puts fields.inspect

它以递归方式尝试处理每个子哈希并将bool字符串转换为bool。

答案 2 :(得分:0)

我假设作为键validation值的哈希值可能包含任何值,而不仅仅是'true''false'。假设你要改变fields,你可以这样做:

convert = { 'true' => true, 'false' => false }
convert.default_proc = ->(_,k) { k }

fields.each { |_,v| v.each { |_, vv|
  vv.each_key { |kkk| vv[kkk] = convert[vv[kkk]] } if vv.is_a? Hash } }
  #=> {"0"=>{"field"=>"something", "field_type"=>"something type",
  #          "validation"=>{"enabled"=>true, "persisted"=>false,
  #          "another thing"=>false}},
  #    "1"=>{"field"=>"something else", "field_type"=>"something else type",
  #          "validation"=>{"enabled"=>true, "persisted"=>false}}}