I don't understand how rails is reading this


I understand the concept of loops. But I don’t understand how rails processes this. Given this code in a rails template…

<%= @a=[1,2,3] %>
<% @a.each do |x| %>
num=<%= x %>
<% end %>

What does Rails do with it?

It seems like the rails interpreter is saying Read line 1, execute it. Line 2, execute @a.each then it sees the ‘do’ so it sees a block is being passed in, then it sees |x| which is still ruby code, then you get this interspersing of html to display, and ruby code to run. And some code will return html which is displayed. What exactly is the rails interpreter doing to deal with that?


Recall that all of the above is in the context of a scoped object. @a is an arbitrarily declared instance variable of that object. The first line defines the variable; the second line iterates over the array that’s defined; and the third line writes to the display each number as an HTML text node, num=1, num=2, and, num=3.


I said I understand the concept of loops. I understand defining variables… And I had no question at all about scope. I was not asking about Ruby here. More about Embedded Ruby. How literal stuff is interspersed with code, how it’s processed. I have since found the answer…

The ERB preprocessor processes it

Anything outside of the tags is just outputted as is … And stuff within the tags is executed… (and in some cases a result returned)

You said num= is an html text node, I am not if sure that’s correct. What if it’s not within a <body> for example, then would it be an HTML text node? And what if it didn’t say num=, if it said <script...> then it would be interpreted as javascript by a browser and I suppose would not be an html text node?


The num= portion is raw text which will be written to the parent container. Without the exercise link it is hard to say what it actually looks like.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.