セットのようなコレクションが必要です。基本的に、長い文字列をスキャンしてコレクションに単語を追加していますが、重複がある場合は検出できるようにしたいと考えています。
If sets aren't available, what's the most efficient way of doing this in Ruby? Brownie points for example code.
セットのようなコレクションが必要です。基本的に、長い文字列をスキャンしてコレクションに単語を追加していますが、重複がある場合は検出できるようにしたいと考えています。
If sets aren't available, what's the most efficient way of doing this in Ruby? Brownie points for example code.
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
ドキュメントから:
a = [ "a", "a", "b", "b", "c" ]
a.uniq #gets you ["a", "b", "c"]
a.uniq.uniq! #gets you nil (no duplicates :)