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.
C0cb3aadb9a66d00df16686f4a1fc312?d=identicon&s=25 Tim Uckun (Guest)
on 2006-05-11 06: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
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2006-05-11 06:54
(Received via mailing list)
On Thu, 11 May 2006, Tim Uckun 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
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2006-05-12 08:53
(Received via mailing list)
Tim Uckun 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
Cd49db0b676767ea4358b1047c4cddd2?d=identicon&s=25 Robin Stocker (Guest)
on 2006-05-12 12:49
(Received via mailing list)
Tim Uckun 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])
A19281bdbc5f08539cdef3d6636f7c4d?d=identicon&s=25 Christoffer Sawicki (Guest)
on 2006-05-12 15:45
(Received via mailing list)
On 5/11/06, Tim Uckun <timuckun@gmail.com> 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.