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 从哪里删除?_Ruby_Hash_Each - Fatal编程技术网

Ruby 从哪里删除?

Ruby 从哪里删除?,ruby,hash,each,Ruby,Hash,Each,下面我编写了一段代码,用来计算字符串中出现的字符数,并以散列形式显示结果。我的想法是在我数完后马上把字符串中的那个字母去掉,这样我们就不会把它放进哈希中不止一次 我最初的代码是: def letter_count_spec(str) letter_count = Hash.new #create hash letter = str.split('') #separate letters letter.each{ |e| if( /[A-Za-z0-9]/.match(e) )

下面我编写了一段代码,用来计算字符串中出现的字符数,并以散列形式显示结果。我的想法是在我数完后马上把字符串中的那个字母去掉,这样我们就不会把它放进哈希中不止一次

我最初的代码是:

def letter_count_spec(str)
letter_count = Hash.new #create hash
letter = str.split('') #separate letters
letter.each{ |e|
    if( /[A-Za-z0-9]/.match(e)  )
        occurances = letter.count{ |x| x==e}
        letter_count[e] = occurances
        letter.delete(e) #delete letter 

    end
}        

return letter_count
end

letter_count_spec("cat")
结果:=>{“c”=>1,“t”=>1}

我输了“a”

所以我试了一下:

def letter_count_spec(str)
letter_count = Hash.new #create hash
letter = str.split('') #separate letters
letter.each{ |e|
    if( /[A-Za-z0-9]/.match(e)  )
        occurances = letter.count{ |x| x==e}
        letter_count[e] = occurances
    end
}        
letter.each{ |e|
    letter.delete(e) #delete letter
}
    return letter_count
end

letter_count_spec("cat")
结果=>{“a”=>1,“c”=>1,“t”=>1}


为什么我需要再次检查数组才能删除?

迭代过程中对集合的修改可能会导致问题,这在注释中已说明

单词计数算法通常包括一个哈希来跟踪单词计数,以及一个迭代器来遍历内容。您不需要修改原始集合。这是一个O(n)解决方案,因为在一般情况下,哈希在更新时具有O(1)复杂性。但是,您的帖子中的计数和删除方法具有O(n^2)复杂性(如果有效的话)


顺便说一句,在Ruby中,使用
do。。。结束多行块的
,除非在某些情况下需要{}。

可能重复的FYI可能重复有许多更好的算法用于此任务,不涉及修改数组。例如,可以使用集合而不是数组来存储要查看的字符,或者可以查看数组一次,并记录每个字符的显示次数。
def letter_count_spec(str)
  letter_count = Hash.new(0) # create hash, and use 0 as the default value
  letter = str.split('')     # separate letters
  letter.each do |e|
    if /[A-Za-z0-9]/.match(e)
      letter_count[e] += 1   # increment count
    end
  end
  letter_count
end