我有一个这样的散列:

params = { :irrelevant => "A String",
           :choice1 => "Oh look, another one",
           :choice2 => "Even more strings",
           :choice3 => "But wait",
           :irrelevant2 => "The last string" }

我想要一个简单的方法来拒绝所有不是choice+int的键。可以是choice1,或者从choice1到choice10。它变化。

我如何用单词选择和后面的一个或多个数字来挑选键?

奖金:

将散列转换为以tab (\t)作为分隔符的字符串。我这样做了,但它花了几行代码。通常大师级的卢比手可以在一行或几行内完成。


当前回答

这是一条解决完整原始问题的直线:

params.select { |k,_| k[/choice/]}.values.join('\t')

但是上面的大多数解决方案都是使用slice或简单的regexp来解决需要提前知道键的情况。

下面是另一种适用于简单和更复杂用例的方法,它在运行时是可切换的

data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }
data.select(&matcher)

现在,这不仅允许在匹配键或值时使用更复杂的逻辑,而且也更容易测试,并且可以在运行时交换匹配逻辑。

解决原问题:

def some_method(hash, matcher) 
  hash.select(&matcher).values.join('\t')
end

params = { :irrelevant => "A String",
           :choice1 => "Oh look, another one",
           :choice2 => "Even more strings",
           :choice3 => "But wait",
           :irrelevant2 => "The last string" }

some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"

其他回答

params = { :irrelevant => "A String",
           :choice1 => "Oh look, another one",
           :choice2 => "Even more strings",
           :choice3 => "But wait",
           :irrelevant2 => "The last string" }

choices = params.select { |key, value| key.to_s[/^choice\d+/] }
#=> {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}

最简单的方法是包含gem 'activesupport'(或gem 'active_support')。

参数个数。切片(:choice1,:choice2,:choice3)

这是一条解决完整原始问题的直线:

params.select { |k,_| k[/choice/]}.values.join('\t')

但是上面的大多数解决方案都是使用slice或简单的regexp来解决需要提前知道键的情况。

下面是另一种适用于简单和更复杂用例的方法,它在运行时是可切换的

data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }
data.select(&matcher)

现在,这不仅允许在匹配键或值时使用更复杂的逻辑,而且也更容易测试,并且可以在运行时交换匹配逻辑。

解决原问题:

def some_method(hash, matcher) 
  hash.select(&matcher).values.join('\t')
end

params = { :irrelevant => "A String",
           :choice1 => "Oh look, another one",
           :choice2 => "Even more strings",
           :choice3 => "But wait",
           :irrelevant2 => "The last string" }

some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"

使用散列切片

{ a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b)
# => {:a=>1, :b=>2}

# If you have an array of keys you want to limit to, you should splat them:
valid_keys = [:mass, :velocity, :time]
search(options.slice(*valid_keys))

如果你想要剩下的哈希值:

params.delete_if {|k, v| ! k.match(/choice[0-9]+/)}

或者如果你只是想要钥匙:

params.keys.delete_if {|k| ! k.match(/choice[0-9]+/)}