ruby 循环中的逗号分隔? [英] Comma separation in a ruby loop?
问题描述
我正在使用 rails 3.1 和 ruby 1.9.2 创建广告服务器.在应用程序中,我在 localhost:3000/ads/script 有页面,它生成 javascript 来显示广告.我正在寻找有关循环的帮助.
I am working on creating a adserver using rails 3.1 and ruby 1.9.2. In the app I have page at localhost:3000/ads/script that generates the javascript to show the ads. Im looking for some help with the loops.
这里是 script.html.erb 的代码:
Here is the code for script.html.erb:
<% @ad.each do |ad| %>
<% if ad.end_date <= Date.today || ad.start_date >= Date.today %>
<% else %>
var advert<%= ad.id %> = ''
advert<%= ad.id %>+='<img class="ad" alt="<%= ad.title %>" src="http://<%= request.env["HTTP_HOST"] %><%= ad.image.url %>" border="0" height="<%= ad.best_height %>" width="<%= ad.best_width %>" />';
advert<%= ad.id %>+='</a>';
advert<%= ad.id %>+='';
<% end %>
<% end %>
document.write( <% @ad.each do |ad|%>
<% if ad.end_date <= Date.today || ad.start_date >= Date.today %>
<% else %>
avert<%= ad.id %>,
<% end %>
<% end %>);
在第二个循环中,我尝试将动态 javascript 变量添加到以逗号分隔的 document.write 中.像document.write(advert1, advert2, advert3)",但在当前代码中,它在每个变量后面放了一个逗号,我需要在后面不要有逗号.知道如何做到这一点吗?
On the second loop I am trying to add dynamic javascript variables to the document.write that are separated with a comma. like "document.write(advert1, advert2, advert3) but with the current code it puts a comma after every variable and I need there to not be a trailing comma. Any idea how to accomplish this?
除了逗号分隔问题,一切正常,但似乎不是很枯燥,似乎可以有更好的方法来执行 if else 语句……这是我的第一个 ruby 应用程序,并且对重构有任何见解将不胜感激.
Aside from the comma separation issue, everything works but it doesn't seem very dry and it seems like there could be a better way to do the if else statement... this is my first ruby app and any insight to refactoring would be much appreciated.
谢谢!
推荐答案
使用连接:
@ad.select{|ad| !(ad.end_date <= Date.today || ad.start_date >= Date.today)}.collect{|ad| "avert#{ad.id}" }.join(",")
这篇关于ruby 循环中的逗号分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!