0
REMOVE_WORDS_ARRAY = ["llc", "co", "corp", "inc", "the"]

businesses_array = import_csv.import('businesses.csv')
print businesses_array
# [["the bakery", "10012"]["law office inc", "10014"]]

businesses_hashes = []
our_hash = {}

businesses_array.each do |business|
  our_hash['BusinessName']  = business[0].strip unless business[0].nil?
  our_hash['BusinessZipCode'] = business[1].strip unless business[1].nil?

  our_hash.each {|key, value|
    our_hash[key] = value.downcase!
    our_hash[key] = (value.split(' ') - REMOVE_WORDS_ARRAY) # only this part doesn't get updated. why?
    our_hash[key] = value.gsub(' ', '+')
  }
  businesses_hashes << our_hash  
  our_hash = {}
end

印刷our_hashすると、名前が小文字になって追加されていることがわかります+が、単語は削除されていません。私は何が欠けていますか?

4

2 に答える 2

4

まあ、それ更新されますが、値は上書きされます。

our_hash[key] = value.downcase! # destructive operation, value mutates in-place
our_hash[key] = (value.split(' ') - REMOVE_WORDS_ARRAY) # remove words and set to hash
our_hash[key] = value.gsub(' ', '+') # use downcased value from the first step, not from the second

3行目をコメントアウトすると、表示されます。また、2行目は配列を返します。最後に追加するのを忘れまし.join(' ')たか?

直し方?1つの流体の動きでそれを行います:)

our_hash[key] = (value.downcase.split(' ') - REMOVE_WORDS_ARRAY).join('+')
于 2013-01-23T16:32:36.300 に答える
1

問題は

  • 文字列を配列に置き換えて、文字列操作を実行しようとしています。
  • (Sergioが指摘しているように)元の操作に戻るvalueため、以前の操作は無関係になります。

さらにいくつかの問題があります。より良いコードは

RemoveWordsRegex = Regexp.union(REMOVE_WORDS_ARRAY.map{|s| /\b#{s}\b/})

businesses_array.each do |name, zip|
  businesses_hashes <<
  {"BusinessName" => name.to_s, "BusinessZipCode" => zip.to_s}
  .values.each{|value|
    value.strip!
    value.downcase!
    value.gsub!(RemoveWordsRegex, "")
    value.gsub!(/\s+/, "+")
  }
end
于 2013-01-23T18:11:39.347 に答える