skip to content

On a Rails listing page, what do number_to_currency(listing.price) and time_ago_in_words(listing.created_at) output, and which defaults trip people up?

level: middleimportance: should knowfreq 38%

answer

  1. format comes from the current locale
  2. no conversion, only formatting
  3. precision 2, delimiter comma, unit $
  4. approximate buckets, no ago suffix
  5. measured against Time.now at render

basics

~20 s

number_to_currency formats a number with the current locale's currency settings (in en: "$1,234.50") but never converts it. time_ago_in_words returns an approximate distance from now such as "about 2 hours" or "3 days", with no "ago" and no past or future direction.

solid answer

~40 s

`number_to_currency` reads unit, format, separator, delimiter and precision from the locale's `number.currency.format` keys; the bundled `en` values give `"$1,234.50"`, rounding to 2 decimals. It only formats: switch the locale to one whose unit is `€` and the same number appears in euros, so for a single-currency shop pass `locale:` or `unit:` explicitly. A non-numeric string passes through (`"$12x34"`) unless you add `raise: true`, and `nil` returns `nil`. `time_ago_in_words(listing.created_at)` compares with `Time.now` and returns bucketed English from the `datetime.distance_in_words` translations: `"less than a minute"`, `"about 1 hour"`, `"3 days"`. It adds no `"ago"` and treats future times the same, so the template writes the suffix itself. The phrase is fixed when the HTML is rendered, so any cached copy of that HTML keeps showing the old phrase.

code

erb · 7 lines
erb
<%# app/views/listings/_listing.html.erb %>
<p class="price"><%= number_to_currency(listing.price, locale: :en) %></p>
<p class="listed">
  Listed <%= time_tag(listing.created_at) { time_ago_in_words(listing.created_at) } %> ago
</p>
<%# price 1234.5  -> $1,234.50
    created 3 days ago -> Listed <time datetime="...">3 days</time> ago %>

go deeper

for a junior

Know both helpers, their typical output for the en locale, and that the template must add the word ago.

for a middle

Explain where the formatting comes from (locale keys and options), the rounding precision, pass-through of bad input, and the directionless distance buckets.

for a senior

Catch the multi-locale currency bug and stale relative times in cached or long-lived pages, and decide where exact timestamps must be exposed.

for a principal

Own the money and time display conventions: one place that formats, explicit currency data, and relative times that stay correct for the pages that need them.

## Two formatting helpers on one card Each card on a vinyl-record listing page shows a **price** and when the record was **listed**. Action View's number and date helpers turn raw values into display text: ```erb <p class="price"><%= number_to_currency(listing.price) %></p> <p>Listed <%= time_ago_in_words(listing.created_at) %> ago</p> ``` Both are plain view helpers available in every template. Both return strings for display, not values to store or compare. ## number_to_currency: formatting from the locale `number_to_currency(number, options)` delegates to `ActiveSupport::NumberHelper` and builds the string from options merged over the current locale's `number.currency.format` translations. The bundled English values are: | Option | en default | Effect | |---|---|---| | `unit` | `"$"` | the currency sign | | `format` | `"%u%n"` | where the unit (`%u`) and number (`%n`) go | | `negative_format` | `"-%u%n"` | layout for negative amounts | | `separator` | `"."` | decimal mark | | `delimiter` | `","` | thousands mark | | `precision` | `2` | digits after the separator | So `number_to_currency(1234.5)` returns `"$1,234.50"`, and `number_to_currency(1234567890.506)` rounds to `"$1,234,567,890.51"`. The traps: - **It never converts.** The helper formats the number it is given. If the app lets a visitor switch to a locale whose `unit` is `€`, the same `19.99` is shown as euros. A shop that sells in one currency should pin it with `locale: :en` or `unit:`, or keep the currency on the listing and format per record. - **Bad input passes through.** A string that is not a number is formatted as text, `"12x34"` becoming `"$12x34"`. `raise: true` raises `ActionView::Helpers::NumberHelper::InvalidNumberError` instead. - **`nil` renders nothing.** A missing price returns `nil`, so the template shows an empty element instead of an error. - **Display rounding hides storage errors.** Prices belong in a `decimal` column or in integer cents; the helper's rounding to 2 places will hide float noise, not fix totals computed from floats. - Option values such as `unit:` and `format:` are HTML-escaped unless already safe, so a sign like `&pound;` should be passed as the real character. ## time_ago_in_words: approximate, directionless English `time_ago_in_words(from_time, options)` is `distance_of_time_in_words(from_time, Time.now, options)`. It measures the gap and maps it to a bucket: 1. under 30 seconds: `"less than a minute"`; 2. 30 seconds to under 90 seconds: `"1 minute"`; then `"2 minutes"` up to `"44 minutes"`; 3. 45 to 89 minutes: `"about 1 hour"`; then `"about 2 hours"` up to a day; 4. from 24 hours up to about a month: `"1 day"`, `"3 days"`; then months, then `"about"`, `"over"` and `"almost"` years. Things people expect and do not get: - **No "ago".** The result is `"3 days"`, so the template writes `Listed ... ago` itself. - **No direction.** The two times are swapped when needed, so `time_ago_in_words(2.hours.from_now)` is also `"about 2 hours"`. A countdown needs its own wording. - **Seconds are coarse** unless you pass `include_seconds: true`, which gives `"less than 5 seconds"`, `"half a minute"` and so on. - **Words come from I18n** under `datetime.distance_in_words`, and the `scope:` option points at a custom set such as a short form. - **It is frozen at render time.** The phrase is computed when the HTML is built. A copy of that HTML served later, from a cache or an open tab, still says "5 minutes". Pair it with `time_tag(listing.created_at)` when client code needs the exact timestamp. ## Putting it together A helper keeps the card template short and puts the choices in one place: ```ruby module ListingsHelper def listing_price(listing) number_to_currency(listing.price, locale: :en) end end ``` The other number helpers follow the same pattern and the same locale lookup: `number_to_percentage`, `number_with_delimiter`, `number_to_human` and `number_to_human_size` all read `number.*` translations and accept the same `locale:` option, so a review that fixes the currency should check them too. ## Mistakes interviewers listen for | Belief | What Action View actually does | |---|---| | switching locale converts the price | only the formatting changes; the number stays the same | | bad input raises | it is formatted as text unless `raise: true` | | `time_ago_in_words` says "3 days ago" | it returns "3 days"; the template adds "ago" | | future times raise or say "in" | the distance has no direction |

  • How would you show prices for a shop that sells in both dollars and euros?
    Store the currency with the amount, for example a `currency` column next to `price`, and format per record with explicit options, such as `number_to_currency(listing.price, unit: "€", format: "%n %u")`. Relying on the visitor's locale would relabel the same number without converting it.
  • What is the difference between time_ago_in_words and distance_of_time_in_words?
    `distance_of_time_in_words(from, to)` measures between any two times; `time_ago_in_words(from)` fixes the second time to `Time.now` (its alias is `distance_of_time_in_words_to_now`). Both return the same bucketed phrases and accept `include_seconds:`, `scope:` and `locale:`.

number_to_currency is a price-tag printer: it prints whatever number you feed it with the sign loaded in the printer, and swapping the sign cartridge does not change the number on the tag.

  • number_to_currency converts the amount when the locale changes
  • time_ago_in_words returns a phrase ending in "ago"
  • time_ago_in_words raises for a time in the future
  • number_to_currency raises on a non-numeric string by default
  • number_to_currency(nil) renders $0.00