Ruby offers built-in support for creating dynamic content or showing customized output to the user with the ERB (Embedded Ruby) library. ERB is commonly used for generating HTML, but it can be used for any text generation purpose.
When you run this script, you’ll see the following output:
In this Ruby example, we’ve used ERB (Embedded Ruby) to create templates, which is analogous to the text/template package in the original example. ERB allows us to embed Ruby code within strings, which is then evaluated when the template is rendered.
We’ve maintained the structure of the original example, demonstrating how to create templates, use variables, work with conditionals, and iterate over collections. The syntax is different, but the concepts are similar:
Instead of {{.}}, we use <%= @variable %> to insert values.
Conditional statements use <% if condition %>...<%else%>...<%end%>.
Loops use <% @array.each do |item| %>...<%end%>.
Ruby’s ERB is more flexible in some ways, as it allows any Ruby code to be embedded and executed within the template. However, this also means that care must be taken to ensure that templates don’t execute unsafe code, especially when working with user input.