这是否有帮助?我不知道你在做什么。
5.times do |count|
puts 'In condition ' + %w(one two three four five)[count]
end
的5.times do |count|
将excecute块五次count
从零开始并且每次递增。 %w(one two three four five)
与["one", "two", "three", "four", "five"]
相同。
如果你想连续做五件不同的事情,你不需要循环。只要把报表中的行:
# do thing 1
# do thing 2
# do thing 3
# ...
编辑:
“我有一个数组,我想通过循环,但阵列中的每个元素需要通过每一次不同的条件然后在第一个条件下重新启动。“
要遍历数组不休,对测试条件的每个元素:
arr = ['sdfhaq', 'aieei', 'xzhzdwz']
loop do
arr.each do |x|
case x
when /..h/
puts 'There was a \'h\' at the third character.'
when /.{6}/
puts 'There were at least six characters.'
else
puts 'None of the above.'
end
end
end
编辑2:
“感谢您的答复,我想要做的是循环通过数组的每个元素应用于10个不同的条件,例如:array [有100个元素]元素1获取条件1元素2继续条件2等等,因为有10个条件是数组中的第11个元素将再次得到条件1等等。条件1条件2条件“
您将需要在数字上使用%
方法。
arr = Array.new(130) # an array of 130 nil elements.
num_conditions = 10
arr.each_with_index do |x, i|
condition = (i + 1) % num_conditions
puts "Condition number = #{condition}"
end
的更多信息:http://ruby-doc.org/core/classes/Fixnum.html#M001059
编辑3:
def send_an_email(email, server)
puts "Sending an email with the text #{email.inspect} to #{server}."
end
email_servers = ['1.1.1.1', '2.2.2.2']
emails = ['How are you doing?', 'When are you coming over?', 'Check out this link!']
emails.each_with_index do |email, i|
send_an_email email, email_servers[i % email_servers.length]
end
您可以修改email_servers
和emails
,并有它仍然可以工作,即使长改变。
对不起,我不明白你是什么要求。为什么要循环? – 2010-06-30 17:20:21
我有一个数组,我想通过循环,但数组中的每个元素需要每次都经历不同的条件,然后在第一个条件重新启动。 – rahrahruby 2010-06-30 17:28:21
您应该编辑您的问题,以添加关于您实际尝试执行的操作的更多详细信息。这听起来像你可能会错误的。 – mckeed 2010-06-30 17:32:27