我正在尝试将for x in y
循环切换为each_with_index
。首先,我正在尝试从for
切换到each
。之前的代码是
...
- 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
....
和rotate_rows_color_group
是app / helpers中的帮手。代码是
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
我做的最初改变就是切换
- for link in @links
是
- @links.each do |link|
这会改变我的观点
到
组名重复出现。这是范围问题吗?
答案 0 :(得分:7)
由于.each
使用了一个块,因此每次输入时都会重新声明其中声明的任何变量。
要避免这种情况,只需在块外声明current_group
:
...
- 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
....