class ERB
[template processor]: en.wikipedia.org/wiki/Template_processor<br>[template engines]: www.ruby-toolbox.com/categories/template_engines<br>[sprintf]: docs.ruby-lang.org/en/master/Kernel.html#method-i-sprintf<br>[rdoc]: ruby.github.io/rdoc<br>[magic comments]: docs.ruby-lang.org/en/master/syntax/comments_rdoc.html#label-Magic+Comments<br>[local binding]: ERB@Local+Binding<br>: docs.ruby-lang.org/en/master/Kernel.html#method-i-binding<br>[expression tags]: ERB@Expression+Tags<br>[execution tags]: ERB@Execution+Tags<br>: docs.ruby-lang.org/en/master/Encoding.html<br>[default binding]: ERB@Default+Binding<br>[comment tags]: ERB@Comment+Tags<br>[binding object]: docs.ruby-lang.org/en/master/Binding.html<br>[augmented binding]: ERB@Augmented+Binding<br>[%q literals]: docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-25q-3A+Non-Interpolable+String+Literals<br><br>of the Ruby Toolbox.
Other popular template processors may found in the [Template Engines][template engines] page
The Ruby Processing System [RDoc], for example, has one that can be used elsewhere.
Various Ruby projects have their own template processors.
## Other Template Processors
“‘
</html>
</body>
</p>
Call for a price, today!
<p>
</ul>
<li>Gem studded eyes… Rubies, of course!</li>
<li>Matz signature on left leg.</li>
<li>Karate-Chop Action!!!</li>
<li>Ignores Perl, Java, and all C variants.</li>
<li>Listens for verbal commands in the Ruby language!</li>
<ul>
<p>Geek’s Best Friend! Responds to Ruby commands…</p>
<h1>Rubysapien (TZ-1002)</h1>
<body>
<head><title>Ruby Toys – Rubysapien</title></head>
<html>
puts erb.result(toy.get_binding)
erb = ERB.new(template)
“‘
Finally, create the ERB object and get the result (omitting some blank lines):
“`
TEMPLATE
</html>
</body>
</p>
<% end %>
Call for a price, today!
<% else %>
Only <%= @cost %>!!!
<% if @cost < 10 %>
<p>
</ul>
<% end %>
<li><%= f %></li>
<% @features.each do |f| %>
<ul>
<p><%= @desc %></p>
<h1><%= @name %> (<%= @code %>)</h1>
<body>
<head><title>Ruby Toys – <%= @name %></title></head>
<html>
template = <<TEMPLATE
“`
Here’s the HTML:
“‘
toy.add_feature(’Gem studded eyes… Rubies, of course!‘)
toy.add_feature(’Matz signature on left leg.‘)
toy.add_feature(’Karate-Chop Action!!!‘)
toy.add_feature(’Ignores Perl, Java, and all C variants.‘)
toy.add_feature(’Listens for verbal commands in the Ruby language!‘)
)
999.95
“Geek’s Best Friend! Responds to Ruby commands…”,
‘Rubysapien’,
toy = Product.new(‘TZ-1002’,
“‘
The template below will need these values:
“`
end
end
binding
def get_binding
# Support templating of member data.
end
@features << feature
def add_feature(feature)
end
@features = []
@cost = cost
@desc = desc
@name = name
@code = code
def initialize(code, name, desc, cost)
class Product
“`
First, here’s a custom class, ‘Product`:
This example shows an HTML template.
## HTML with Embedded Ruby
“`
James Edward Gray II
Thanks for your patience.
* Answer Questions on Ruby Talk
* Document Modules
* Run Ruby Quiz
especially:
I want you to know that my team will keep working on the issues,
addressed.
Just wanted to send a quick note assuring that your needs are being
Community:
Subject: Addressing Needs
To: Community Spokesman <spokesman@ruby_community.org>
From: James Edward Gray II <james@grayproductions.net>
puts erb.result(binding)
erb = ERB.new(template, trim_mode: ’%<>‘)
“`
Finally, create the ERB object and get the result
“`
’Answer Questions on Ruby Talk’ ]
‘Document Modules’,
priorities = [ ‘Run Ruby Quiz’,
to = ‘Community Spokesman <spokesman@ruby_community.org>’
“‘
The template will need these:
“`
}
James Edward Gray II
Thanks for your patience.
% end
* <%= priority %>
% priorities.each do |priority|
<%# ignore numerous minor requests – focus on priorities %>
especially:
I want you to know that my team will keep working on the issues,
addressed.
Just wanted to send a quick note assuring that your needs are being
<%= to %>:
Subject: Addressing Needs
To: <%= to %>
From: James Edward Gray II <james@grayproductions.net>
template = %q{
“`
this avoids problems with backslashes.
(see [%q literals][%q literals]);
it uses the literal notation `’%q{ … }‘` to define the template
Here’s a plain-text template;
## Plain Text with Embedded Ruby
“‘
u.txt:1000:in ’<main>‘: undefined local variable or method ’nosuch’ for main (NameError)
erb.result
erb.location = [‘u.txt’, 999]
“‘
You can use method #location= to set both values:
“`
t.txt:556:in ’<main>‘: undefined local variable or method ’nosuch’ for main (NameError)
erb.result
erb.lineno = 555
erb.filename = ‘t.txt’
“‘
that are more meaningful in your context:
You can use methods #filename= and #lineno= to assign values
“`
(erb):1:in ’<main>‘: undefined local variable or method ’nosuch’ for main (NameError)
erb.result
erb.lineno # => 0
erb.filename # => nil
“‘
these initial values are reported as `’(erb)‘` and `1`, respectively:
Initially, those values are `nil` and `0`, respectively;
the file name comes from method #filename, the line number from method #lineno.
it includes a file name (if available) and a line number;
When ERB reports an error,
“`
erb = ERB.new(template)
template = ’<%= nosuch %>‘
“`
Consider this template (containing an error):
## Error Reporting
“`
erb.result.encoding # => #<Encoding:Big5>
erb.encoding # => #<Encoding:Big5>
template.encoding # => #<Encoding:UTF-8>
erb = ERB.new(template)
TEMPLATE
<%# Comment. %>
<%#-*- coding: Big5 -*-%>
template = <<TEMPLATE
“`
at the top of the given template:
You can specify a different encoding by adding a [magic comment][magic comments]
“`
erb.result.encoding # => #<Encoding:UTF-8>
erb.encoding # => #<Encoding:UTF-8>
template.encoding # => #<Encoding:UTF-8>
erb = ERB.new(template)
TEMPLATE
<%# Comment. %>
template = <<TEMPLATE
“`
the result string will also have that encoding.
which is by default the encoding of the template string;
An ERB object has an [encoding],
## Encodings
“`
# => “Some stuff;”
ERB.new(’Some stuff;<% # Note to self: figure out what the stuff is. %> more stuff.‘).result
“`
the cited code consists entirely of a Ruby-style comment (which is of course ignored):
In this example, the tag begins with `’<% #‘`, and so is an execution tag, not a comment tag;
Note that the beginning of the tag must be `’<%#‘`, not `’<% #‘`.
A comment tag may appear anywhere in the template.
“`
ERB.new(template).result # => “Some stuff; more stuff.”
template = ’Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.‘
“`
Example:
(generating no text in the result).
it removes the entire comment tag
When you call method #result,
where text is the text of the comment.
its syntax is `<%# text %>`,
You can embed a comment in a template using a *comment tag*;
### Comment Tags
- `’%<>‘`: Enable shorthand and omit newline for each line starting with `’<%‘` and ending with `’%>‘`.
- `’%>‘`: Enable shorthand and omit newline for each line ending with `’%>‘`.
- `’%-‘`: Enable shorthand and omit each blank line ending with `’-%>‘`.
You can combine certain trim modes:
#### Combining Trim Modes
“`
“foo 3.4.5n”
“3.4.5foo n”
ERB.new(template, trim_mode: ’<>‘).result.lines.each {|line| puts line.inspect }
“`
for each line that both begins with `’<%‘` and ends with `’%>‘`:
You can give `trim_mode: ’<>‘` to suppress the trailing newline
“`
“3.4.5foo foo 3.4.5”
ERB.new(template, trim_mode: ’>‘).result.lines.each {|line| puts line.inspect }
“`
for each line that ends with `’%<‘` (regardless of its beginning):
You can give `trim_mode: ’>‘` to suppress the trailing newline
“`
“foo 3.4.5n”
“foo n”
“3.4.5n”
“n”
ERB.new(template).result.lines.each {|line| puts line.inspect }
“`
With keyword argument `trim_mode` not given, all newlines go into the result:
“`
TEMPLATE
foo <%= RUBY_VERSION %>
foo <% RUBY_VERSION %>
<%= RUBY_VERSION %>
<% RUBY_VERSION %>
template = <<TEMPLATE
“`
Consider this template:
#### Suppressing Unwanted Newlines
“`
ERB.new(template).result.lines.each {|line| puts line.inspect } # Raises SyntaxError.
“`
It is an error to use the trailing `’-%>‘` notation without `trim_mode: ’-‘`:
“`
“3.4.5n”
ERB.new(template, trim_mode: ’-‘).result.lines.each {|line| puts line.inspect }
TEMPLATE
<% end -%>
<%= RUBY_VERSION %>
<% if true -%>
template = <<TEMPLATE
“`
whose source line ends with `-%>` (instead of `%>`):
You can give `trim_mode: ’-‘`, you can suppress each blank line
“`
“n”
“3.4.5n”
“n”
ERB.new(template).result.lines.each {|line| puts line.inspect }
TEMPLATE
<% end %>
<%= RUBY_VERSION %>
<% if true %>
template = <<TEMPLATE
“`
all blank lines go into the result:
With keyword argument `trim_mode` not given,
#### Suppressing Unwanted Blank Lines
(no leading whitespace).
Note that in the shorthand format, the character `’%‘` must be the first character in the code line
“`
* Answer Questions on Ruby Talk
* Document Modules
* Run Ruby Quiz
puts erb.result(binding)
’Answer Questions on Ruby Talk’ ]
‘Document Modules’,
priorities = [ ‘Run Ruby Quiz’,
erb = ERB.new(template, trim_mode: ‘%’)
TEMPLATE
% end
* <%= priority %>
% priorities.each do |priority|
template = <<TEMPLATE
“‘
this example uses the shorthand format `% code` instead of `<% code %>`:
You can use keyword argument `trim_mode: ’%‘` to enable a shorthand format for execution tags;
#### Shorthand Format for Execution Tags
“`
# => “n* 0,0nn* 0,1nn* 0,2nn* 1,0nn* 1,1nn* 1,2nn* 2,0nn* 2,1nn* 2,2nn”
ERB.new(template).result
TEMPLATE
%>
end
end
<%
* <%=i%>,<%=j%>
%>
(0..2).each do |j|
(0..2).each do |i|
<%
template = <<TEMPLATE
“`
The execution tag may also contain multiple lines of code:
“`
# => “n2025-09-09 11:36:02 -0500nnn2025-09-09 11:36:03 -0500nnn2025-09-09 11:36:04 -0500nnn”
ERB.new(template).result
TEMPLATE
<% end %>
<% sleep(1) # Let’s make the times different. %>
<%= Time.now %>
<% 3.times do %>
template = <<TEMPLATE
“‘
and the Ruby code may itself contain regular Ruby comments:
Other, non-control, lines of Ruby code may be interleaved with the text,
“`
# => “nSunnnMonnnTuennWednnThunnFrinnSatnn”
ERB.new(template).result
TEMPLATE
<% end %>
<%= dayname %>
<% Date::ABBR_DAYNAMES.each do |dayname| %>
template = <<TEMPLATE
“`
Loop:
Note that the interleaved text may itself contain expression tags:
“`
# => “nOops!nn”
erb.result(binding)
verbosity = false
# => “nAn error has occurred.nn”
erb.result(binding)
verbosity = true
erb = ERB.new(template)
TEMPLATE
<% end %>
Oops!
<% else %>
An error has occurred.
<% if verbosity %>
template = <<TEMPLATE
“`
Conditional:
such as a conditional, a loop, or a `case` statements.
You can interleave text with execution tags to form a control structure
“`
ERB.new(’foo <%Dir.chdir(“C:/”)%> bar’).result # => “foo bar”
“‘
Whitespace before and after the embedded code is optional:
“`
ERB.new(’foo <% Dir.chdir(“C:/”) %> bar’).result # => “foo bar”
“‘
(generating no text in the result):
the method executes the code and removes the entire execution tag
When you call method #result,
where code is any valid Ruby code.
Its syntax is `<% code %>`,
You can embed Ruby executable code in template using an *execution tag*.
### Execution Tags
“`
# => “My appointment is on Wednesday.”
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
“`
and that such whitespace is stripped from the result.
is allowed but not required,
Note that whitespace before and after the expression
“`
# => “Yesterday was Sunday.”
ERB.new(’Yesterday was <%= Date::DAYNAMES[Date.today.wday - 1] %>.‘).result
# => “Tomorrow will be Tuesday.”
ERB.new(’Tomorrow will be <%= Date::DAYNAMES[Date.today.wday + 1] %>.‘).result
# => “Today is Monday.”
ERB.new(’Today is <%= Date::DAYNAMES %>.‘).result
“`
the method evaluates the expression and replaces the entire expression tag with the expression’s value:
When you call method #result,
where expression is any valid Ruby expression.
Its syntax is ‘<%= expression %>`,
You can embed a Ruby expression in a template using an *expression tag*.
### Expression Tags
in the result, the entire tag is to be omitted.
- [Comment tag][comment tags]: the tag contains comment code;
in the result, the entire tag is to be replaced with the run-time value of the code.
- [Execution tag][execution tags]: the tag contains Ruby code;
in the result, the entire tag is to be replaced with the run-time value of the expression.
- [Expression tag][expression tags]: the tag contains a Ruby expression;
These are the tags available in ERB:
The examples above use expression tags.
## Tags
“`
The current process is irb.
The Ruby copyright is “ruby - Copyright © 1993-2025 Yukihiro Matsumoto”.
The current value of variable baz is 4.
The current value of variable bar is 3.
puts erb.result_with_hash(hash)
hash = {bar: 3, baz: 4}
“`
in a new binding (derived from #new_toplevel):
This call passes a hash that causes `bar` and `baz` to be defined
“`
puts erb.result(binding) # Raises NameError.
puts erb.result # Raises NameError.
“`
are not defined in either the default binding or the local binding.
Both of these calls raise `NameError`, because `bar` and `baz`
“`
erb = ERB.new(template)
TEMPLATE
The current process is <%= $0 %>.
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
The current value of variable baz is <%= baz %>.
The current value of variable bar is <%= bar %>.
template = <<TEMPLATE
“`
in a copy of the default binding:
the passed hash has name/value pairs that are to be used to define and assign variables
is to use method #result_with_hash(hash);
Another way to make variable bindings (but not constant bindings) available
### Augmented Binding
“`
The current process is irb.
The Ruby copyright is “ruby - Copyright © 1993-2025 Yukihiro Matsumoto”.
The current value of variable foo is 2.
The current value of constant Foo is 1.
puts erb.result(binding)
“`
you can call #result with the local binding:
To make the locally-defined constants and variables available,
“`
erb.result # Raises NameError.
“`
they are not defined in the default binding:
This call below raises `NameError` because although `Foo` and `foo` are defined locally,
“`
erb = ERB.new(template)
TEMPLATE
The current process is <%= $0 %>.
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
The current value of variable foo is <%= foo %>.
The current value of constant Foo is <%= Foo %>.
template = <<TEMPLATE
foo = 2 # Defines local variable foo.
Foo = 1 # Defines local constant Foo.
“`
that refers to a a constant or variable that is not defined there:
The default binding is not sufficient for an expression
### Local Binding
(The current process is `irb` because that’s where we’re doing these examples!)
“‘
The current process is irb.
The Ruby copyright is “ruby - Copyright © 1993-2025 Yukihiro Matsumoto”.
puts ERB.new(template).result
TEMPLATE
The current process is <%= $0 %>.
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
template = <<TEMPLATE
“`
these expression tags refer only to Ruby’s global constant ‘RUBY_COPYRIGHT` and global variable `$0`:
That binding is sufficient for an expression tag that refers only to Ruby’s constants and variables;
which are those for Ruby’s constants and variables.
This binding has the bindings defined by Ruby itself,
the method uses its default binding: the one returned by method #new_toplevel.
When you pass no ‘binding` argument to method #result,
### Default Binding
- [Augmented binding][augmented binding]
- [Local binding][local binding].
- [Default binding][default binding].
There are three ways to provide the required binding:
The binding object provides the bindings for expressions in [expression tags][expression tags].
requires a [Binding object][binding object] as its argument.
A call to method #result, which produces the formatted result string,
## Bindings
“`
# => “The magic word is xyzzy.”
erb.result(binding)
magic_word = ’xyzzy’
“‘
As before, the ERB object may be re-used:
that contains the value of `magic_word`.
4. Method call `erb.result(binding)` generates a string
3. `magic_word = ’abracadabra’‘ assigns a value to variable `magic_word`.
note that `magic_word` need not be defined before the ERB object is created.
2. The string is put into a new ERB object, and stored in variable `erb`;
Its embedded [expression tag][expression tags] `’<%= magic_word %>‘` has a variable name, `magic_word`.
1. As before, a plain-text string is assigned to variable `template`.
Details:
“`
# => “The magic word is abracadabra.”
erb.result(binding)
magic_word = ’abracadabra’
erb = ERB.new(template)
template = ‘The magic word is <%= magic_word %>.’
“‘
Another example:
“`
# => “The time is 2025-09-09 10:49:33 -0500.”
erb.result
“`
ERB object may be re-used:
The
as computed at the time of the call.
4. Method call `erb.result` generates a string that contains the run-time value of `Time.now`,
2. The string is put into a new ERB object, and stored in variable `erb`.
Its embedded [expression tag][expression tags] `’<%= Time.now %>‘` includes a Ruby expression, `Time.now`.
1. A plain-text string is assigned to variable `template`.
Details:
“`
# => “The time is 2025-09-09 10:49:26 -0500.”
erb.result
erb = ERB.new(template)
template = ’The time is <%= Time.now %>.‘
“`
Here’s a simple example of ERB in action:
## Some Simple Examples
ERB.new(template).result # => “Some stuff; more stuff.”
template = ‘Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.’
in the result, the entire tag is omitted.
each begins with ‘’<%#‘`, ends with `’%>‘`; contains comment text;
- [Comment tags][comment tags]:
File.read(’t.txt’) # => “Some stuff.”
ERB.new(template).result
template = ‘<% File.write(“t.txt”, “Some stuff.”) %>’
each begins with ‘’<%=‘`, ends with `’%>‘`; contains Ruby code to be executed:
- [Execution tags][execution tags]:
ERB.new(’Today is <%= Date::DAYNAMES %>.‘).result # => “Today is Monday.”
because its expression `Date::DAYNAMES` is globally defined.
The below call to #result need not pass a binding,
which contains the binding of variable `magic_word` to its string value `’xyzzy’‘.
The above call to #result passes argument `binding`,
erb.result(binding) # => “The magic word is xyzzy.”
magic_word = ’xyzzy’
erb = ERB.new(template)
template = ‘The magic word is <%= magic_word %>.’
in the result, the value of the expression replaces the entire tag:
each begins with ‘’<%‘`, ends with `’%>‘`; contains a Ruby expression;
- [Expression tags][expression tags]:
ERB supports tags of three kinds:
- You can call instance method ERB#result to get the result.
- You can create an ERB object to store the template.
- You can create a template: a plain-text string that includes specially formatted tags..
Here’s how ERB works:
## In Brief
“‘
require ’erb’
“‘
(examples on this page assume that this has been done):
Before you can use ERB, you must first require it
## Usage
is an easy-to-use, but also very powerful, [template processor][template processor].
Class ERB (the name stands for **Embedded Ruby**)
:markup: markdown
def self.version
self.version -> string
:call-seq:
:markup: markdown
def self.version VERSION end
def def_class(superklass=Object, methodname='result')
```