Forum: Ruby A more elegant way to do this?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tim U. (Guest)
on 2006-05-11 08:33
(Received via mailing list)
Can anybody suggest a more elegant and rubyish way to do this?

I am reading a YAML file and then trying to iterate over arrays and
hashes that may or may not be there.

 unless conf['hosts'][hostname]['groups'].nil?
   conf['hosts'][hostname]['groups'].each { |group|
     unless conf['crontables'][group].nil?
         conf['crontables'][group].each { | tab_item|
           tab_entries << tab_item
         }
      end #Unless
    }
  end #unless
unknown (Guest)
on 2006-05-11 08:54
(Received via mailing list)
On Thu, 11 May 2006, Tim U. wrote:

>        }
>     end #Unless
>   }
> end #unless
>


   array = lambda{|x| x || []}

   array[conf['hosts'][hostname]['groups']].each {|group|
      array[conf['crontables'][group]].each {|tab_item|
        tab_entries << tab_item
      }
   }


hth.

-a
Joel VanderWerf (Guest)
on 2006-05-12 10:53
(Received via mailing list)
Tim U. wrote:
>         }
>      end #Unless
>    }
>  end #unless

A slight variation on the other suggestions:

def each_element_of(enum)
  enum and enum.each {|elt| yield elt}
end

each_element_of conf['hosts'][hostname]['groups'] do |group|
  each_element_of conf['crontables'][group] do |tab_item|
    tab_entries << tab_item
  end
end


Another slight variation:

conf['hosts'][hostname]['groups'].to_a.each do |group|
  conf['crontables'][group].to_a.each do | tab_item|
    tab_entries << tab_item
  end
end
Robin S. (Guest)
on 2006-05-12 14:49
(Received via mailing list)
Tim U. wrote:
>         conf['crontables'][group].each { | tab_item|
>           tab_entries << tab_item
>         }

A small suggestion for the above if tab_entries is an array:

   tab_entries.concat(conf['crontables'][group])
Christoffer S. (Guest)
on 2006-05-12 17:45
(Received via mailing list)
On 5/11/06, Tim U. <removed_email_address@domain.invalid> wrote:
>          }
>       end #Unless
>     }
>   end #unless
>

nil.to_a # => []

conf['hosts'][hostname]['groups'].to_a.each do |group|
  conf['crontables'][group].to_a.each do |tab_item|
    tab_entries << tab_item
  end
end
This topic is locked and can not be replied to.