/ ruby-on-rails

Rails i18n pluralization

Sometimes we need to show different text based on some count. Like for example:

if box_count == 0
  message = "No boxes present"
elsif box_count == 1
  message = "Only 1 box present"
else
  message = "There are #{box_count} boxes"
end

You can refactor this to make use of i18n locales power. In en.yml you can do -

en:
  boxes:
    message:
      zero: No boxes present
      one: Only 1 box present
      other: There are %{count} boxes

And in view we can use: <%= t('boxes.message', count: 2) %>