64

あるフィルターから別のフィルターにキーと値のペアをフィルター処理する方法を理解しようとしています

たとえば、このハッシュを取得したい

x = { "one" => "one", "two" => "two", "three" => "three"}

y = x.some_function

y == { "one" => "one", "two" => "two"}

ご協力いただきありがとうございます

編集: おそらく、この例では、ホワイトリスト フィルターとして動作するようにしたいことに言及する必要があります。つまり、私は自分が望んでいないことではなく、自分が何を望んでいるのかを知っています。

4

7 に答える 7

105

Rails の ActiveSupport ライブラリもスライスを提供し、キー レベルでハッシュを処理することを除きます。

y = x.slice("one", "two") # => { "one" => "one", "two" => "two" }
y = x.except("three")     # => { "one" => "one", "two" => "two" }
x.slice!("one", "two")    # x is now { "one" => "one", "two" => "two" }

これらはとてもいいもので、いつも使っています。

于 2009-04-03T20:18:53.377 に答える
56

多分これはあなたが望むものです。

wanted_keys = %w[one two]
x = { "one" => "one", "two" => "two", "three" => "three"}
x.select { |key,_| wanted_keys.include? key }

配列やハッシュなどに含まれているEnumerableミックスインは、select / reject / each/etcなどの便利なメソッドを多数提供します。riEnumerableを使用してドキュメントを確認することをお勧めします。

于 2009-04-03T05:01:36.310 に答える
49

You can just use the built in Hash function reject.

x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.reject {|key,value| key == "three" }
y == { "one" => "one", "two" => "two"}

You can put whatever logic you want into the reject, and if the block returns true it will skip that key,value in the new hash.

于 2009-04-02T22:29:39.093 に答える
8

@scottdの回答を少し改善します。レールを使用していて、必要なもののリストがある場合は、スライスからパラメーターとしてリストを展開できます。例えば

hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
hash.slice(*keys_whitelist)

また、レールがなくても、どの Ruby バージョンでも、次のことができます。

hash = { "one" => "one", "two" => "two", "three" => "three"}
keys_whitelist = %W(one two)
Hash[hash.find_all{|k,v| keys_whitelist.include?(k)}] 
于 2013-07-18T19:56:14.733 に答える
7
y = x.reject {|k,v| k == "three"}
于 2009-04-02T22:29:44.020 に答える
7

みんなの答えを組み合わせて、この解決策を思いつきました:

 wanted_keys = %w[one two]
 x = { "one" => "one", "two" => "two", "three" => "three"}
 x.reject { |key,_| !wanted_keys.include? key }
 =>{ "one" => "one", "two" => "two"}

助けてくれてありがとう!

編集:

上記は1.8.7+で動作します

以下は 1.9+ で動作します:

x.select { |キー,_| want_keys.include? 鍵 }

于 2009-04-03T13:04:09.740 に答える