Reason #122 • May 2nd, 2026

Templating with ERB

ERB (Embedded Ruby) is a templating system that allows you to embed Ruby code within a text document. It is commonly used for generating HTML, but can be used for any text-based format. It is bundled with Ruby as a standard gem, making it widely available and easy to use.

Ruby
require "erb"

template = ERB.new("Hello, <%= name %>!")
template.result_with_hash(name: "Alice")
# => "Hello, Alice!"

yaml_template = ERB.new <<~YAML
  name: <%= name %>
  age: <%= age %>
YAML

yaml_template.result_with_hash(name: "Bob", age: 30)
# => "name: Bob\nage: 30\n"
    

If you've used Rails, you've likely noticed how controller instance variables are made available in views. Rails does more than this, but the core idea is that controller instance variables are collected into an assigns hash, then copied onto the view object:

Ruby
require "erb"

class View
  def initialize(name)
    @name = name
  end

  def render(template)
    template.result(binding)
  end
end

template = ERB.new("Hello, <%= @name %>!")
view = View.new("Charlie")
view.render(template)
# => "Hello, Charlie!"
    

Worth noting that Rails uses Erubi under the hood, which, among other things, adds out of the box HTML escaping support.

History

ERB first shipped in Ruby 1.8.0, released in 2003.

Reason #123 ?