questforimprovement questforimprovement - 3 months ago 12
HTML Question

content_tag :tr block in simple English

I'm a beginner to Rails and I saw this block of code somewhere and was wondering what the code exactly does in relation to the HEADER variable that is defined as an array of the seven days.

def header
content_tag :tr do
HEADER.map { |day| content_tag :th, day }.join.html_safe
end
end

Answer

This method is able to create HTML like this :

<tr>
  <th> first day </th>
  <th> second day </th>
  .....................
  <th> Seventh day </th>
</tr>

Explanation :

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block.

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

The Join method used to convert the output array to a string and html_safe is used to proper rendering of HTML on web page.

Comments