Over a million developers have joined DZone.

Helpful Extensions To Core Ruby Classes

DZone's Guide to

Helpful Extensions To Core Ruby Classes

· ·
Free Resource
If you find yourself doing this a lot:

<% if @collection.any? -%>

    <% for item in @collection %>
  1. <%= item %>
  2. <% end -%>
<% end -%>
...you might want to extend two Ruby core classes to automagically print out HTML-lists. Extend Array with: def to_html_list(type = :ol) self.inject("<#{type}>\n") { |output, item| output << "\t
  • #{item}
  • \n" } << " \n" if self.any? end
    Now you can produce both OL (default) and UL lists. You can easily convert a Hash into a DL-list by extending it like so: def to_html_list self.inject("
    \n") { |o, p| o << "\t
    \n" } << "
    \n" if self.any? end
    Extending core classes is a bit dangerous but I use these in almost every Rails project.

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}