Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby if hash keys include text, return hash key

Tags:

ruby

hash

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.

like image 334
Luigi Avatar asked Mar 27 '26 10:03

Luigi


1 Answers

Use find:

if result = hash.keys.find {|k| k.include? number}
  #do some work
end
like image 138
Maurício Linhares Avatar answered Mar 30 '26 11:03

Maurício Linhares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!