簡體   English   中英

Ruby Do循環和迭代

[英]Ruby Do loop and iteration

是否有內置的方法來寫記錄號,這樣我就不必創建變量並增加它了? 此時只開發實踐。 file.recnumber

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

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

<% end %>

我認為您正在尋找的each_with_index ,將索引作為第二個參數傳遞給該塊。

如果您想做比with_index each復雜的事情,那么最新的Ruby版本還包括with_index方法,您可以將其鏈接到任何Enumerable方法上以獲得帶有索引的版本。 例如:

('a'..'z').map.with_index {|letter, index| "#{index} #{letter.upcase}" }
<% files.each_with_index do |file, index| %>
    ...
<% end %>

實際上,io對象和文件對象確實具有lineno方法。

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

另一種選擇是僅使用HTML有序列表:

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

將為您提供如下內容,您可以使用CSS輕松設置其樣式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM