2011-11-10 116 views
1

是否有一个内置的方法来写入记录数字,以便我不必创建一个变量并增加它?只是在这一点上开发实践。 file.recnumber红宝石做循环和迭代

<% i = 1%> 
<% @files.each do |file| %> 

<%= i %>. <%= file %> (<%= file.size %>)k<br /> 
<% i = i + 1%> 

<% end %> 

回答

3
<% files.each_with_index do |file, index| %> 
    ... 
<% end %> 
0

另一种方法是只使用一个HTML有序列表:

<ol> 
<% ["one", "two", "three"].each do |file| %> 
    <li>file <%= file %></li> 
<% end %> 
</ol> 

会给你像下面这样,你可以用CSS轻松风格:

1. file one 
2. file two 
3. file three 
4

我想你正在寻找each_with_index,它将索引作为第二个参数传递给块。

如果您想要做一些比each更复杂的事情,最新版本的Ruby还包含一个with_index方法,您可以链接到任何Enumerable方法以获取带有索引的版本。例如:

('a'..'z').map.with_index {|letter, index| "#{index} #{letter.upcase}" } 
1

事实上,IO对象和文件对象确实有LINENO方法。

File.open("test.txt") do |file| 
    file.each{|line| puts "#{file.lineno}: #{line}"} 
end