35

セットのようなコレクションが必要です。基本的に、長い文字列をスキャンしてコレクションに単語を追加していますが、重複がある場合は検出できるようにしたいと考えています。

If sets aren't available, what's the most efficient way of doing this in Ruby? Brownie points for example code.

4

2 に答える 2

74

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
end
于 2009-03-02T12:40:33.437 に答える
21

ドキュメントから:

a = [ "a", "a", "b", "b", "c" ]
a.uniq  #gets you   ["a", "b", "c"]
a.uniq.uniq! #gets you nil (no duplicates :)
于 2009-03-02T11:57:25.350 に答える