Michael Durrant
Michael Durrant

Reputation: 96484

Why is ruby's '.each' giving different results to using 'for'?

I am trying to switch a for x in y loop to a each_with_index. First, I am trying to switch from for to each. The code before is

...
- row_bg_color_group = 'row_color_group_1'
- for link in @links
  - construct_hyperlink(link.url_address, link.alt_text)
  - if link.group.group_name != (current_group ||= '')
    - display_group = current_group = link.group.group_name
    - row_bg_color_group = rotate_rows_color_group
  - else
    - display_group = ''
  %tr{:class => "#{row_bg_color_group}"}
    %td
      = link_to display_group, link.group, {"title" => link.group.group_description}
    %td
      %span#mainLink
        = sanitize @address_url
    %td= link.version_number
....

and rotate_rows_color_group is a helper in app/helpers. The code is

def rotate_rows_color_group
  if session[:group_shading] == 'true' || params[:show]
    cycle('row_color_group_1 color_group_1', 'row_color_group_2 color_group_2', 'row_color_group_3 color_group_3')
  else
    cycle('row_color_group_1', 'row_color_group_2', 'row_color_group_3')
  end 
end 

The initial change I made is just to switch

- for link in @links

to be

- @links.each do |link|

This is changing my view from enter image description here

to

enter image description here

The group name gets repeated. Is it a scope issue?

Upvotes: 2

Views: 62

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

Since .each uses a block, any variable declared within it will be re-declared each time it is entered.

To avoid this, simply declare current_group outside the block:

...
- row_bg_color_group = 'row_color_group_1'
- current_group = ''
- @links.each do |link|
  - construct_hyperlink(link.url_address, link.alt_text)
  - if link.group.group_name != current_group
    - display_group = current_group = link.group.group_name
    - row_bg_color_group = rotate_rows_color_group
  - else
    - display_group = ''
  %tr{:class => "#{row_bg_color_group}"}
    %td
      = link_to display_group, link.group, {"title" => link.group.group_description}
    %td
      %span#mainLink
        = sanitize @address_url
    %td= link.version_number
....

Upvotes: 7

Related Questions