class ERB

Class ERB (the name stands for Embedded Ruby) is an easy-to-use, but also very powerful, template processor.

Like method sprintf, ERB can format run-time data into a string. ERB, however,s is much more powerful.

In simplest terms:

ERB is commonly used to produce:

Usage

Before you can use ERB, you must first require it (examples on this page assume that this has been done):

require 'erb'

In Brief

# Expression tag: begins with '<%', ends with '%>'.
# This expression does not need the local binding.
ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result # => "Today is Monday."
# This expression tag does need the local binding.
magic_word = 'xyzzy'
template.result(binding) # => "The magic word is xyzzy."

Execution tag: begins with '<%=', ends with '%>'.
s = '<% File.write("t.txt", "Some stuff.") %>'
ERB.new(s).result
File.read('t.txt') # => "Some stuff."

# Comment tag: begins with '<%#', ends with '%>'.
s = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.'
ERB.new(s).result # => "Some stuff; more stuff."

Some Simple Examples

Here’s a simple example of ERB in action:

s = 'The time is <%= Time.now %>.'
template = ERB.new(s)
template.result
# => "The time is 2025-09-09 10:49:26 -0500."

Details:

  1. A plain-text string is assigned to variable s. Its embedded expression tag '<%= Time.now %>' includes a Ruby expression, Time.now.

  2. The string is put into a new ERB object, and stored in variable template.

  3. Method call template.result generates a string that contains the run-time value of Time.now, as computed at the time of the call.

The template may be re-used:

template.result
# => "The time is 2025-09-09 10:49:33 -0500."

Another example:

s = 'The magic word is <%= magic_word %>.'
template = ERB.new(s)
magic_word = 'abracadabra'
# => "abracadabra"
template.result(binding)
# => "The magic word is abracadabra."

Details:

  1. As before, a plain-text string is assigned to variable s. Its embedded expression tag '<%= magic_word %>' has a variable name, magic_word.

  2. The string is put into a new ERB object, and stored in variable template; note that magic_word need not be defined before the ERB object is created.

  3. magic_word = 'abracadabra' assigns a value to variable magic_word.

  4. Method call template.result(binding) generates a string that contains the value of magic_word.

As before, the template may be re-used:

magic_word = 'xyzzy'
template.result(binding)
# => "The magic word is xyzzy."

Bindings

The first example above passed no argument to method result; the second example passed argument binding.

Here’s why:

Tags

The examples above use expression tags. These are the tags available in ERB:

Expression Tags

You can embed a Ruby expression in a template using an expression tag.

Its syntax is <%= expression %>, where expression is any valid Ruby expression.

When you call method result, the method evaluates the expression and replaces the entire expression tag with the expression’s value:

ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result
# => "Today is Monday."
ERB.new('Tomorrow will be <%= Date::DAYNAMES[Date.today.wday + 1] %>.').result
# => "Tomorrow will be Tuesday."
ERB.new('Yesterday was <%= Date::DAYNAMES[Date.today.wday - 1] %>.').result
# => "Yesterday was Sunday."

Note that whitespace before and after the expression is allowed but not required, and that such whitespace is stripped from the result.

ERB.new('My appointment is on <%=Date::DAYNAMES[Date.today.wday + 2]%>.').result
# => "My appointment is on Wednesday."
ERB.new('My appointment is on <%=     Date::DAYNAMES[Date.today.wday + 2]    %>.').result
# => "My appointment is on Wednesday."

Execution Tags

You can embed Ruby executable code in template using an execution tag.

Its syntax is <% code %>, where code is any valid Ruby code.

When you call method result, the method executes the code and removes the entire execution tag (generating no text in the result).

You can interleave text with execution tags to form a control structure such as a conditional, a loop, or a case statements.

Conditional:

s = <<EOT
<% if verbosity %>
An error has occurred.
<% else %>
Oops!
<% end %>
EOT
template = ERB.new(s)
verbosity = true
template.result(binding)
# => "\nAn error has occurred.\n\n"
verbosity = false
template.result(binding)
# => "\nOops!\n\n"

Note that the interleaved text may itself contain expression tags:

Loop:

s = <<EOT
<% Date::ABBR_DAYNAMES.each do |dayname| %>
<%= dayname %>
<% end %>
EOT
ERB.new(s).result
# => "\nSun\n\nMon\n\nTue\n\nWed\n\nThu\n\nFri\n\nSat\n\n"

Other, non-control, lines of Ruby code may be interleaved with the text, and the Ruby code may itself contain regular Ruby comments:

s = <<EOT
<% 3.times do %>
<%= Time.now %>
<% sleep(1) # Let's make the times different. %>
<% end %>
EOT
ERB.new(s).result
# => "\n2025-09-09 11:36:02 -0500\n\n\n2025-09-09 11:36:03 -0500\n\n\n2025-09-09 11:36:04 -0500\n\n\n"

The execution tag may also contain multiple lines of code:

s = <<EOT
<%
  (0..2).each do |i|
    (0..2).each do |j|
%>
* <%=i%>,<%=j%>
<%
    end
  end
%>
EOT
ERB.new(s).result
# => "\n* 0,0\n\n* 0,1\n\n* 0,2\n\n* 1,0\n\n* 1,1\n\n* 1,2\n\n* 2,0\n\n* 2,1\n\n* 2,2\n\n"

You can use keyword argument trim_mode to make certain adjustments to the processing; see ERB.new.

In particular, you can give trim_mode: '%' to enable a shorthand format for execution tags; this example uses the shorthand format % code instead of <% code %>:

s = <<EOT
% priorities.each do |priority|
  * <%= priority %>
% end
EOT
template = ERB.new(s, trim_mode: '%')
priorities = [ 'Run Ruby Quiz',
               'Document Modules',
               'Answer Questions on Ruby Talk' ]
puts template.result(binding)
  * Run Ruby Quiz
  * Document Modules
  * Answer Questions on Ruby Talk

Note that in the shorthand format, the character '%' must be the first character in the code line (no leading whitespace).

Comment Tags

You can embed a comment in a template using a comment tag; its syntax is <%# text %>, where text is the text of the comment.

When you call method result, it removes the entire comment tag (generating no text in the result).

Example:

s = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.'
ERB.new(s).result # => "Some stuff; more stuff."

A comment tag may appear anywhere in the template text.

Note that the beginning of the tag must be '<%#', not '<% #'.

In this example, the tag begins with '<% #', and so is an execution tag, not a comment tag; the cited code consists entirely of a Ruby-style comment (which is of course ignored):

ERB.new('Some stuff;<% # Note to self: figure out what the stuff is. %> more stuff.').result
# => "Some stuff;"

Encodings

In general, an ERB result string (or Ruby code generated by ERB) has the same encoding as the string originally passed to ERB.new; see Encoding.

You can specify the output encoding by adding a magic comment at the top of the given string:

s = <<EOF
<%#-*- coding: Big5 -*-%>

Some text.
EOF
# => "<%#-*- coding: Big5 -*-%>\n\nSome text.\n"
s.encoding
# => #<Encoding:UTF-8>
ERB.new(s).result.encoding
# => #<Encoding:Big5>

Plain Text Example

Here’s a plain-text string; it uses the literal notation '%q{ ... }' to define the string (see %q literals); this avoids problems with backslashes.

s = %q{
From:  James Edward Gray II <james@grayproductions.net>
To:  <%= to %>
Subject:  Addressing Needs

<%= to[/\w+/] %>:

Just wanted to send a quick note assuring that your needs are being
addressed.

I want you to know that my team will keep working on the issues,
especially:

<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
  * <%= priority %>
% end

Thanks for your patience.

James Edward Gray II
}

The template will need these:

to = 'Community Spokesman <spokesman@ruby_community.org>'
priorities = [ 'Run Ruby Quiz',
               'Document Modules',
               'Answer Questions on Ruby Talk' ]

Finally, make the template and get the result

template = ERB.new(s, trim_mode: '%<>')
puts template.result(binding)

From:  James Edward Gray II <james@grayproductions.net>
To:  Community Spokesman <spokesman@ruby_community.org>
Subject:  Addressing Needs

Community:

Just wanted to send a quick note assuring that your needs are being
addressed.

I want you to know that my team will keep working on the issues,
especially:

* Run Ruby Quiz
* Document Modules
* Answer Questions on Ruby Talk

Thanks for your patience.

James Edward Gray II

HTML Example

This example shows an HTML template.

First, here’s a custom class, Product:

class Product
  def initialize(code, name, desc, cost)
    @code = code
    @name = name
    @desc = desc
    @cost = cost
    @features = []
  end

  def add_feature(feature)
    @features << feature
  end

  # Support templating of member data.
  def get_binding
    binding
  end

end

The template below will need these values:

toy = Product.new('TZ-1002',
                  'Rubysapien',
                  "Geek's Best Friend!  Responds to Ruby commands...",
                  999.95
                  )
toy.add_feature('Listens for verbal commands in the Ruby language!')
toy.add_feature('Ignores Perl, Java, and all C variants.')
toy.add_feature('Karate-Chop Action!!!')
toy.add_feature('Matz signature on left leg.')
toy.add_feature('Gem studded eyes... Rubies, of course!')

Here’s the HTML:

s = <<EOT
<html>
  <head><title>Ruby Toys -- <%= @name %></title></head>
  <body>
    <h1><%= @name %> (<%= @code %>)</h1>
    <p><%= @desc %></p>
    <ul>
      <% @features.each do |f| %>
        <li><b><%= f %></b></li>
      <% end %>
    </ul>
    <p>
      <% if @cost < 10 %>
        <b>Only <%= @cost %>!!!</b>
      <% else %>
         Call for a price, today!
      <% end %>
    </p>
  </body>
</html>
EOT

Finally, build the template and get the result (omitting some blank lines):

template = ERB.new(s)
puts template.result(toy.get_binding)
<html>
  <head><title>Ruby Toys -- Rubysapien</title></head>
  <body>
    <h1>Rubysapien (TZ-1002)</h1>
    <p>Geek's Best Friend!  Responds to Ruby commands...</p>
    <ul>
        <li><b>Listens for verbal commands in the Ruby language!</b></li>
        <li><b>Ignores Perl, Java, and all C variants.</b></li>
        <li><b>Karate-Chop Action!!!</b></li>
        <li><b>Matz signature on left leg.</b></li>
        <li><b>Gem studded eyes... Rubies, of course!</b></li>
    </ul>
    <p>
         Call for a price, today!
    </p>
  </body>
</html>

Other Template Processors

Various Ruby projects have their own template processors. The Ruby Processing System RDoc, for example, has one that can be used elsewhere.

Other popular template processors may found in the Template Engines page of the Ruby Toolbox.