Spl*_*lin 80 ruby each loops ruby-on-rails
如果我有一个循环,如
users.each do |u|
#some code
end
Run Code Online (Sandbox Code Playgroud)
用户是多个用户的哈希值.什么是最简单的条件逻辑,看你是否在用户哈希中的最后一个用户,并且只想为最后一个用户执行特定的代码,所以像
users.each do |u|
#code for everyone
#conditional code for last user
#code for the last user
end
end
Run Code Online (Sandbox Code Playgroud)
谢谢
Rap*_*met 137
users.each_with_index do |u, index|
# some code
if index == users.size - 1
# code for the last user
end
end
Run Code Online (Sandbox Code Playgroud)
mea*_*gar 38
如果这是一个非此即彼/或情况,在那里你将一些代码给所有,但最后一个用户,然后一些独特的代码,只有最后一个用户的另一种解决方案可能更为合适.
但是,您似乎为所有用户运行相同的代码,并为最后一个用户运行一些其他代码.如果是这种情况,这似乎更正确,更清楚地表明您的意图:
users.each do |u|
#code for everyone
end
users.last.do_stuff() # code for last user
Run Code Online (Sandbox Code Playgroud)
Alt*_*gos 18
我认为最好的方法是:
users.each do |u|
#code for everyone
if u.equal?(users.last)
#code for the last user
end
end
Run Code Online (Sandbox Code Playgroud)
Tej*_*eni 10
你试过each_with_index吗?
users.each_with_index do |u, i|
if users.size-1 == i
#code for last items
end
end
Run Code Online (Sandbox Code Playgroud)
h = { :a => :aa, :b => :bb }
h.each_with_index do |(k,v), i|
puts ' Put last element logic here' if i == h.size - 1
end
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是从 StopIteration 中拯救:
user_list = users.each
begin
while true do
user = user_list.next
user.do_something
end
rescue StopIteration
user.do_something
end
Run Code Online (Sandbox Code Playgroud)
您也可以在非此即彼的情况下使用 @meager 的方法,在这种情况下,您将一些代码应用于除最后一个用户之外的所有用户,然后将一些唯一的代码仅应用于最后一个用户。
users[0..-2].each do |u|
#code for everyone except the last one, if the array size is 1 it gets never executed
end
users.last.do_stuff() # code for last user
Run Code Online (Sandbox Code Playgroud)
这样你就不需要条件了!
| 归档时间: |
|
| 查看次数: |
54648 次 |
| 最近记录: |