【问题标题】:Ruby Do loop and iterationRuby Do 循环和迭代
【发布时间】:2011-12-26 11:25:54
【问题描述】:
是否有写入记录编号的内置方法,这样我就不必创建变量并增加它?只是在这一点上发展实践。 file.recnumber?
<% i = 1%>
<% @files.each do |file| %>
<%= i %>. <%= file %> (<%= file.size %>)k<br />
<% i = i + 1%>
<% end %>
【问题讨论】:
标签:
ruby-on-rails
ruby
iteration
【解决方案1】:
<% files.each_with_index do |file, index| %>
...
<% end %>
【解决方案2】:
另一种选择是只使用 HTML 有序列表:
<ol>
<% ["one", "two", "three"].each do |file| %>
<li>file <%= file %></li>
<% end %>
</ol>
将为您提供以下内容,您可以使用 CSS 轻松设置样式:
1. file one
2. file two
3. file three
【解决方案3】:
我认为您正在寻找each_with_index,它将索引作为第二个参数传递给块。
如果你想做一些比each 更复杂的事情,Ruby 的最新版本还包括一个with_index 方法,你可以将它链接到任何 Enumerable 方法以获取具有索引的版本。例如:
('a'..'z').map.with_index {|letter, index| "#{index} #{letter.upcase}" }
【解决方案4】:
其实io对象和文件对象确实有一个lineno方法。
File.open("test.txt") do |file|
file.each{|line| puts "#{file.lineno}: #{line}"}
end