在当前用户的帖子上显示一个数字

Jus*_*tin 0 ruby-on-rails ruby-on-rails-4

这听起来像一个简单的问题,但由于某种原因,我迷路了.

在我的用户个人资料页面中,我正在显示他们的所有帖子.如果他们有3个帖子,我想展示这样的东西.

1. Post one title
2. Post two title
3. Post three title
Run Code Online (Sandbox Code Playgroud)

所以它显示了帖子左边的数字.这不能是帖子的ID.有谁知道如何解决这个问题?

jkl*_*ina 7

是的,退房Enumerable#each_with_index.所以你可以这样做:

@posts.each_with_index do |post, index|
  puts "#{index} #{post}"
end
Run Code Online (Sandbox Code Playgroud)

  • 只需使用`"#{index + 1}#{post}"`. (2认同)
  • 实际上也有一种方法.`Enumerable #with_index` http://www.ruby-doc.org/core-2.1.0/Enumerator.html#method-i-with_index.这让你提供一个偏移量. (2认同)