Why does each method require that the value it loops be assigned to a variable?

Working on Rails and finding a lack of knowledge in my understanding of the method each

.

Don't know why the method each

requires a variable|message|

<% @messages.each do |message| %>
    <h2><%= message.title %></h2>
    <%= link_to "View Message", message_path(message), class: "btn btn-default" %>
<% end %>

      

+3


source to share


3 answers


As you walk through, @messages

you need to refer to each element in some way to make it available to your code. Ruby does this by passing each element to the block, one at a time, as a variable. The pipe syntax is used in Ruby to refer to block variables in any block context, not just each

.

Ruby is not going to decide for itself what, when you repeat @messages

, each element should be named message

. You need to make this decision explicitly and assign the variable name in pipes. You don't need to call the variable message

. You can name it hot_dog

. But you need to assign the element to something, otherwise you won't be able to access it and what's the point of the loop?



<% @messages.each do |hot_dog| %>
    <h2><%= hot_dog.title %></h2>
    <%= link_to "View Message", message_path(hot_dog), class: "btn btn-default" %>
<% end %>

      

+3


source


Not sure why each method needs a variable |message|

It doesn't require. You can omit it very much.



<% @messages.each do %>

      

But in this case, what are you going to output in yours <h2>

?

+7


source


each

does not change the value self

inside or outside the block. For example:

class Foo
  def bar1; "hello"; end
  def bar2; [1].each { puts bar1 }
end
Foo.new.bar2 # => "hello"

      

In this example, the method call is the bar1

same as what is specified puts self.bar1

, so you need to maintain the same value self

as outside the block.

If you want to set a value self

in a block for the current iterator, you can use a method like this:

def bound_each(&blk)
  each { |x| x.instance_eval &blk }
end
[1].bound_each { puts self } # => 1

      

However, as far as I know, there is nothing like this in the core of Ruby or Rails.

Also see fooobar.com/questions/2423875 / ... for a similar method that constrains self

to Enumerable ( [1]

here)

+1


source







All Articles