将数组名称分配给变量并在 RoR 中排序
绝对的 RoR 新手,我试图在循环中渲染多个联赛,每次递增 div_#,这是一个精简版本,没有 html。当我硬编码要排序的 div_1 或 div_2 时,它可以工作,但 div_name 不起作用,即使它具有正确的内容,我需要将其视为数组。
<% div_1 = Array.new
div_1 << { :Name => 'Rob', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
div_2 = Array.new
div_2 << { :Name => 'Gavin', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
for i in (1..2)
i = i.to_s
div_name = "div_" + i
div_name.sort_by { |position| position[:Points] }.reverse!.each do |position| %>
<%= position[:Name] %>
Absolute RoR newbie here, I'm trying to render out multiple leagues in a loop, incrementing the div_# each time, here's a cut down version, without the html. It works when I hard code div_1 or div_2 to be sorted, but div_name doesn't work, even though it has the right contents I need it to be seen as the array.
<% div_1 = Array.new
div_1 << { :Name => 'Rob', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
div_2 = Array.new
div_2 << { :Name => 'Gavin', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
for i in (1..2)
i = i.to_s
div_name = "div_" + i
div_name.sort_by { |position| position[:Points] }.reverse!.each do |position| %>
<%= position[:Name] %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有很多问题:
div_1
现在是一个包含单个元素的数组,该元素是一个哈希值。如果数组中只有一个元素,则不需要数组。这个循环的块在哪里?在该语句之后,
i
仍然未定义,因此当您调用时,您将得到一个 NameError。
即使
i == 1
,div_name
也将是一个值为“div_1”的字符串,而不是您所设置的div_1
变量的副本或实例。定义如上。现在,您尝试对字符串调用
sort_by
,但它不会对此做出响应,因为它没有意义。您没有在此范围内定义名为
position
的变量。此外,当您发现自己在
<% %>
标记内的视图中放置了大量逻辑时,这表明您需要将该代码移至其他地方,例如控制器。您可以在控制器中将@positions
定义并计算为哈希数组,然后在视图中执行以下操作:There are lots of problems here:
div_1
is now an array with a single element, which is a hash. You don't need an array if you'll just have one element in it.Where's the block for this loop? After that statement,
i
is still undefined, so when you callyou'll get a NameError.
Even if
i == 1
,div_name
will be a string with value 'div_1', and not a copy or instance of thediv_1
variable you define above.Now you're trying to call
sort_by
on a string, which doesn't respond to that, because it doesn't make sense.You don't have a variable named
position
defined at this scope.Also, when you find yourself putting lots of logic inside of a view within
<% %>
tags, that's a sign that you need to move that code elsewhere, like to the controller. You could define and calculate@positions
as an array of hashes in the controller, and then in the view do something like: