Ruby:过滤哈希键的最简单方法? [英] Ruby: Easiest Way to Filter Hash Keys?

查看:50
本文介绍了Ruby:过滤哈希键的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的哈希:

I have a hash that looks something like this:

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

而且我想要一种简单的方法来拒绝所有不是choice+int 的键.它可以是选择 1 或选择 1 到选择 10.因人而异.

And I want a simple way to reject all the keys that aren't choice+int. It could be choice1, or choice1 through choice10. It varies.

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

How do I single out the keys with just the word choice and a digit or digits after them?

奖励:

将哈希转换为以制表符 (\t) 作为分隔符的字符串.我这样做了,但需要几行代码.通常鲁比西斯大师可以在一行左右的时间内完成.

Turn the hash into a string with tab (\t) as a delimiter. I did this, but it took several lines of code. Usually master Rubicians can do it in one or so lines.

推荐答案

Edit to original answer:即使这是答案(截至此评论时)是选定的答案,原始答案此答案的版本已过时.

Edit to original answer: Even though this is answer (as of the time of this comment) is the selected answer, the original version of this answer is outdated.

我在这里添加一个更新,以帮助其他人避免像我一样被这个答案误导.

I'm adding an update here to help others avoid getting sidetracked by this answer like I did.

正如其他答案所提到的,Ruby >= 2.5 添加了以前仅在 Rails 中可用的 Hash#slice 方法.

As the other answer mentions, Ruby >= 2.5 added the Hash#slice method which was previously only available in Rails.

示例:

> { one: 1, two: 2, three: 3 }.slice(:one, :two)
=> {:one=>1, :two=>2}

编辑结束.接下来是原始答案,我想如果您使用的是 Ruby <2.5 没有 Rails,虽然我认为这种情况在这一点上并不常见.

End of edit. What follows is the original answer which I guess will be useful if you're on Ruby < 2.5 without Rails, although I imagine that case is pretty uncommon at this point.

如果您使用 Ruby,则可以使用 select 方法.您需要将键从 Symbol 转换为 String 以进行正则表达式匹配.这将为您提供一个新的哈希,其中只有其中的选择.

If you're using Ruby, you can use the select method. You'll need to convert the key from a Symbol to a String to do the regexp match. This will give you a new Hash with just the choices in it.

choices = params.select { |key, value| key.to_s.match(/^choice\d+/) }

或者你可以使用 delete_if 并修改现有的哈希,例如

or you can use delete_if and modify the existing Hash e.g.

params.delete_if { |key, value| !key.to_s.match(/choice\d+/) }

或者如果它只是键而不是您想要的值,那么您可以这样做:

or if it is just the keys and not the values you want then you can do:

params.keys.select { |key| key.to_s.match(/^choice\d+/) }

这将给出一个键数组,例如[:choice1, :choice2, :choice3]

and this will give the just an Array of the keys e.g. [:choice1, :choice2, :choice3]

这篇关于Ruby:过滤哈希键的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆