AKWF AKWF - 5 months ago 12
Ruby Question

How can I attempt to iterate a Hash in Ruby when the object may be nil?

I find myself having to do this all the time, and when I'm in a hurry I wrap it in a conditional:

if !myhash.blank?
hash.each do |k,v|
do_something
end
end


or:

myhash.map{|k,v| do_something} unless myhash.blank?


There must be something cleaner.

Answer

I tend to use to_h to hide the "is it nil" test:

hash.to_h.each do |k,v|
  # something
end

If hash is already a Hash then hash.to_h is hash, if hash.nil? then hash.to_h is { }.

Similarly, I use to_a for arrays:

array.to_a.each { |e| ... }

to_s for strings, to_i for integers (when I want to treat nil as zero), ...