我需要一个像集合一样的集合。基本上,我正在扫描一个长字符串,并将单词添加到集合中,但我希望能够检测到何时存在重复项。
如果集合不可用,在Ruby中最有效的方法是什么?Brownie点出了示例代码。
发布于 2009-03-02 11:57:25
在documentation中:
a = [ "a", "a", "b", "b", "c" ]
a.uniq #gets you ["a", "b", "c"]
a.uniq.uniq! #gets you nil (no duplicates :)发布于 2009-03-02 12:40:33
在ruby中有一个Set类。你可以这样使用它:
require 'set'
set = Set.new
string = "a very very long string"
string.scan(/\w+/).each do |word|
unless set.add?( word )
# logic here for the duplicates
end
end不过,我想知道在这种情况下,您是否想要计算实例数,下面的示例会更好:
instances = Hash.new { |h, k| h[k] = 0 }
string.scan(/\w+/).each do |word|
instances[word] += 1
endhttps://stackoverflow.com/questions/602034
复制相似问题