私は配列を持っています。ハッシュを作成して、「X は配列内にありますか?」とすぐに尋ねることができるようにしたいと考えています。
perl には、これを行う簡単な (そして速い) 方法があります。
my @array = qw( 1 2 3 );
my %hash;
@hash{@array} = undef;
これにより、次のようなハッシュが生成されます。
{
1 => undef,
2 => undef,
3 => undef,
}
私がRubyで思いついた最高のものは次のとおりです。
array = [1, 2, 3]
hash = Hash[array.map {|x| [x, nil]}]
与える:
{1=>nil, 2=>nil, 3=>nil}
より良いRubyの方法はありますか?
編集1
いいえ、Array.include? 良い考えではありません。その遅い。O(1) ではなく O(n) でクエリを実行します。私の例の配列には、簡潔にするために 3 つの要素がありました。実際のものには百万の要素があると仮定します。少しベンチマークを行いましょう。
#!/usr/bin/ruby -w
require 'benchmark'
array = (1..1_000_000).to_a
hash = Hash[array.map {|x| [x, nil]}]
Benchmark.bm(15) do |x|
x.report("Array.include?") { 1000.times { array.include?(500_000) } }
x.report("Hash.include?") { 1000.times { hash.include?(500_000) } }
end
プロデュース:
user system total real
Array.include? 46.190000 0.160000 46.350000 ( 46.593477)
Hash.include? 0.000000 0.000000 0.000000 ( 0.000523)