ruby如果散列键包含文本,则返回散列键(ruby if hash keys include text, return hash key)

编程入门 行业动态 更新时间:2024-10-28 20:22:48
ruby如果散列键包含文本,则返回散列键(ruby if hash keys include text, return hash key)

我有这样的哈希:

hash = {2013 => 'one', 2014 => 'two'}

和一个可变number :

number = 13

我需要搜索所有的哈希键,如果键中包含number ,我需要返回该键。 现在我有这个:

if hash.keys.any? {|k| k.include? number} #do some work end

这是有效的,但实际上我需要在k确实包含number的情况下返回k ,而不仅仅是检查它。 如何以上面的块“if”格式轻松编写。

I have a hash like so:

hash = {2013 => 'one', 2014 => 'two'}

and a variable number:

number = 13

I need to search through all of my hash keys and if number is included in a key, I need to return that key. Right now I have this:

if hash.keys.any? {|k| k.include? number} #do some work end

That works, but I actually need to return k in the case that k does include number, not just check for it. How can I write that easily in a block "if" format like above.

最满意答案

使用find :

if result = hash.keys.find {|k| k.include? number} #do some work end

Use find:

if result = hash.keys.find {|k| k.include? number} #do some work end

更多推荐

本文发布于:2023-08-01 14:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1359287.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   hash   ruby   散列键   keys

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!