Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash: return the first key value under which is not nil

Tags:

ruby

Say I have a hash

hash = {a:1, b:false, c:nil}

& a series of keys somewhere: [:c, :b, :a]. Is there a Ruby idiom for returning such a key value under which != nil?

The obv

[:c, :b, :a].select {|key| hash[key] != nil}.first     # returns :b

seems too long.

like image 363
a tired guy Avatar asked Apr 08 '26 02:04

a tired guy


2 Answers

For that I think Enumerable#find might work:

find(ifnone = nil) { |obj| block } → obj or nil
find(ifnone = nil) → an_enumerator

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

In your case it'd return the first for which block is not nil:

p %i[c b a].find { |key| !{ a: 1, b: nil, c: nil }[key].nil? } # :a
p %i[c b a].find { |key| !{ a: 1, b: 1, c: nil }[key].nil? }   # :b
like image 137
Sebastian Palma Avatar answered Apr 10 '26 21:04

Sebastian Palma


If you want to filter elements with falsy values, you can use the following expressions.

keys = [:d, :c, :b, :a]
hash = { a: 1, b: nil, c: nil, d: 2 }
keys.select(&hash)
#  => [:d, :a]

If you want to filter elements with exactly nil as a value, it is not correct, as Mr. Ilya wrote.

like image 30
set0gut1 Avatar answered Apr 10 '26 20:04

set0gut1



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!