AKWF AKWF - 1 year ago 53
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|


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

There must be something cleaner.

Answer Source

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

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

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), ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download