Skip to content

Using blank and compact in Ruby on Rails to help output incomplete data

Posted on 06 January 2007

Often I want to display a set of address fields, but only show the ones that have been filled in by the user.

For example if I have an Applicant with several address fields, then in the applicant model I will do the following:

 def address
   [address_1,
    address_2,
    address_3,
    town,
    county,
    postcode].collect{|a| a unless a.blank? }.compact
 end

The blank check makes the empty strings nil and the compact method removes the nil items. So you are left with only the fields with content output to the screen.

Then in the view I can do:

applicant.address.join("<br />")

Using the address method will output all the address fields the user has filled in, without me having to check each one individually if it has content.

The join method just put's <br />'s after each line as to create the following inside address tags:

<address>
25 The Street</br>
The City</br>
The County</br>
GU1 1AA
</address>

View the snippets archive ››

2 comments made

Mark Van Holstyn commented on 06 Jan 07 at 11:17

I think you could accomplish the same thing in RoR with [....].select{ |a| a.blank? }

Brian commented on 22 Jun 07 at 03:31

I think Mark means:
[....].reject{|a| a.blank?}

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com