rukia_kuchiki_21
rukia_kuchiki_21

Reputation: 1329

Find first hash key with nil value

def job_ids
 {
   job_id:   r.job_id,
   job_2_id: r.job_2_id,
   job_3_id: r.job_3_id
 }
end

def available_job_id
   job_ids.find { |_k, v| v.nil? }[0].to_s
end

im checking which key has the first value of nil,and then i convert it to string.

what's the best way to do it?

This seems to be dirty?

job_ids.find { |_k, v| v.nil? }[0].to_s

UPDATE: here's the desired output so far...

[79] pry(main)> job_ids.find{|k, v| v.nil?}[0].to_s
=> "job_2_id"

Upvotes: 0

Views: 186

Answers (2)

Johnny Dương
Johnny Dương

Reputation: 772

Try this

job_ids.key(nil).to_s

Upvotes: 3

yez
yez

Reputation: 2378

You can just use key

job_ids.key(nil).to_s
#=> "job_2_id"

Upvotes: 1

Related Questions