在Ruby中修改对哈希值的引用

时间:2016-08-10 04:31:09

标签: ruby string reference hashmap blackboard

我是Ruby新手,我有一个JSON数据集,我使用stympy's Faker去识别。我更愿意通过引用更改哈希值中的值。

我尝试过更改作业,例如。 key['v] = namea[1]data['cachedBook']['rows'][key][value] = namea[1]但我收到no implicit conversion of Array into String错误。这是有道理的,因为每个都是一个数组本身,但我不确定如何继续这个。

单行,例如data['cachedBook']['rows']看起来像这样:

    [{"v":"Sijpkes_PreviewUser","c":"LN","uid":"9######","iuid":"3####7","avail":true,"sortval":"Sijpkes_PreviewUser"},
{"v":"Paul","c":"FN","sortval":"Paul"},
{"v":"#####_previewuser","c":"UN"},
    {"v":"","c":"SI"},{"v":"30 June 2016","c":"LA","sortval":1467261918000},
    {"v":"Available","c":"AV"},[],[],[],[],[],[],
    {"v":"-","tv":"","numAtt":"0","c":"374595"},[],[],
    {"v":"-","tv":"","numAtt":"0","c":"374596"},[],[],[],
    {"v":0,"tv":"0.0","mp":840,"or":"y","c":"362275"},
    {"v":0,"tv":"0.0","mp":99.99999,"or":"y","c":"389721"}] 

键和值被解释为前两个条目。 已使用#### s删除了敏感数据。

Ruby代码:

data['cachedBook']['rows'].each do |key, value|
  fullname = Faker::Name.name
  namea = fullname.split(' ')

  str = "OLD: " + String(key['v']) + " " + String(value['v']) +"\n";
  puts str

  if ["Ms.", "Mr.", "Dr.", "Miss", "Mrs."].any? { |needle| fullname.include? needle  }
      key['v'] = namea[2]
      value['v'] = namea[1]
      value['sortval'] = namea[1]
  else
      key['v'] = namea[1]
      value['v'] = namea[0]
      value['sortval'] = namea[1]
  end

  str = "\nNEW: \nFullname: "+String(fullname)+"\nConverted surname: "+ String(key['v']) + "\n\t firstname: " + String(value['v'])
  puts str
end

puts data

1 个答案:

答案 0 :(得分:0)

好的,这是一次很棒的学习练习!

我遇到的问题分为两部分:

  1. 来自JSON.parse的JSON输出是一个哈希,但哈希存储了数组,所以我的代码破了。查看上面的示例数据行,它包含一些空数组:... [],[],[] ...

  2. 我误解了每个人是如何使用哈希的,我假设key, value(类似于每个jquery)但原始每个语句中的key, value实际上都计算了前两个数组元素。

  3. 所以这是我修改过的代码:

    data['cachedBook']['rows'].map! { |row|
      fullname = Faker::Name.name
      namea = fullname.split(' ')
    
      row.each { |val|
    
      if val.class == Hash
          newval = val.clone
            if ["Ms.", "Mr.", "Dr.", "Miss", "Mrs."].any? { |needle| fullname.include? needle  }
                  if val.key?("c") && val["c"] == "LN"
                    newval["v"] = namea[1]
                    newval["sortval"] = namea[1]
                  end
                  if val.key?("c") && val["c"] == "FN"
                    newval["v"] = namea[2]
                    newval["sortval"] = namea[2]
                  end
            else
                if val.key?("c") && val["c"] == "LN"
                  newval["v"] = namea[0]
                  newval["sortval"] = namea[0]
                end
                if val.key?("c") && val["c"] == "FN"
                  newval["v"] = namea[1]
                  newval["sortval"] = namea[1]
                end
            end
        val.merge!(newval)
      end
      }
    }