Skip to content

Ruby things I learned this week: present?, presence, and memoization

In this week’s “things I learned this week,” my good buddy Trevor pointed me to some useful Active Support methods that I hadn’t used before: present? and presence.

present? allows you to avoid a !(foo.blank?) statement. It does the same thing (literally), but in Ruby style, it’s more expressive of your intent (“Is it there? then okay, carry on).

Meanwhile, presence is kind of nice. Noticed it while I was checking out present? in GitHub. From the code:

  #   state   = params[:state]   if params[:state].present?
  #   country = params[:country] if params[:country].present?
  #   region  = state || country || 'US'
  # ...becomes:
  #   region = params[:state].presence || params[:country].presence || 'US'

Can we take a moment to appreciate nice, in-code documentation? Love it.

And besides those things, he shared a cool post about memoization, how you can use ||= begin to work the magic. Check it out!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.