Skip to content

Getting Started

Cyril Kato edited this page Jan 20, 2026 · 1 revision

Table of Contents

Getting Started

This guide will help you install AcceptLanguage and write your first language matching code in under 5 minutes.

Installation

Add the gem to your Gemfile:

gem "accept_language"

Then run:

bundle install

Or install it directly:

gem install accept_language

Your First Match

The library has a simple two-step workflow: parse the header, then match against your available languages.

require "accept_language"

# Step 1: Parse the Accept-Language header
parser = AcceptLanguage.parse("fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7")

# Step 2: Match against your available languages
parser.match(:en, :fr, :de)
# => :fr

In this example, the user prefers Swiss French (fr-CH), but since your app doesn't support it, the gem returns :fr (French) as the next best match.

One-Liner Syntax

You can chain the methods for a more concise syntax:

AcceptLanguage.parse("fr-CH, fr;q=0.9, en;q=0.8").match(:en, :fr, :"fr-CH")
# => :"fr-CH"

Understanding the Result

The match method returns:

  • A Symbol — the best matching language from your available options
  • nil — if no acceptable match is found
# Match found
AcceptLanguage.parse("ja, en;q=0.8").match(:en, :fr)
# => :en

# No match found
AcceptLanguage.parse("ja, zh").match(:en, :fr)
# => nil

Handling Missing Headers

When the Accept-Language header is absent or empty, the parser returns nil for any match:

AcceptLanguage.parse(nil).match(:en, :fr)
# => nil

AcceptLanguage.parse("").match(:en, :fr)
# => nil

This makes it easy to fall back to a default locale:

header = nil  # or request.env["HTTP_ACCEPT_LANGUAGE"]
locale = AcceptLanguage.parse(header).match(:en, :fr, :de) || :en

locale
# => :en (your default)

Quick Reference

Code Result Why
AcceptLanguage.parse("en, fr;q=0.8").match(:en, :fr) :en English has higher quality (1.0 vs 0.8)
AcceptLanguage.parse("en").match(:"en-US", :"en-GB") :"en-US" Prefix matching: en matches en-US
AcceptLanguage.parse("de, *;q=0.5").match(:ja) :ja Wildcard * matches any language
AcceptLanguage.parse("*, en;q=0").match(:en, :fr) :fr English is excluded (q=0)
AcceptLanguage.parse("ja").match(:en, :fr) nil No match available

What's Next?

Now that you have the basics, explore the core concepts:

Or jump directly to framework integration:

Clone this wiki locally