Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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
    #{p[0]}
    \n\t
    #{p[1]}
    \n" } << "
    \n" if self.any? end
    Extending core classes is a bit dangerous but I use these in almost every Rails project.
    Topics:

    Opinions expressed by DZone contributors are their own.

    THE DZONE NEWSLETTER

    Dev Resources & Solutions Straight to Your Inbox

    Thanks for subscribing!

    Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

    X

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

    {{ parent.tldr }}

    {{ parent.urlSource.name }}