我有以下代码:
@referred_emails = Array.new
@referred_emails = params.select{|k, v| k.start_with?('referred_') }.values
puts "referred emails array: " + @referred_emails.inspect.to_s
@referred_emails.each_with_index do |referred_email, index|
puts "index is #{index}. referred_email is #{referred_email}"
end
这是服务日志:
15:25:34 web.1 | referred emails array: ["theiremail1", "theiremail2", "theiremail3"]
15:25:34 web.1 | index is 0. referred_email is theiremail1
15:25:35 web.1 | index is 1. referred_email is theiremail3
如您所见,由于某种原因,数据库中的第二个元素被跳过。它应该输出以下内容:
15:25:34 web.1 | referred emails array: ["theiremail1", "theiremail2", "theiremail3"]
15:25:34 web.1 | index is 0. referred_email is theiremail1
15:25:34 web.1 | index is 1. referred_email is theiremail2
15:25:35 web.1 | index is 2. referred_email is theiremail3
但由于某种原因,它一直在跳过第二个。
以下是参数:
15:25:34 web.1 | Parameters: {"utf8"=>"✓",
"authenticity_token"=>"f7f0idqcQpXG/XzhQYCaEj3xQHLiQz1Nf1z9gF3CMxM=",
"referrer_email"=>"", "referrer_name"=>"", "referred_0"=>"theiremail1",
"referred_1"=>"theiremail2", "referred_2"=>"theiremail3", "commit"=>"SUBMIT"}
为什么跳过第二个元素?
答案 0 :(得分:0)
不确定最终会出现什么问题但是,一切似乎至少对我有用:
params = {"referrer_email"=>"", "referrer_name"=>"", "referred_0"=>"theiremail1", "referred_1"=>"theiremail2", "referred_2"=>"theiremail3"}
params.select{|k, v| k.include?('referred_') }.values
#=> ["theiremail1", "theiremail2", "theiremail3"]
或:
params.select{|k, v| k.start_with?('referred_') }.values
#=> ["theiremail1", "theiremail2", "theiremail3"]
或:
params.select{|k, v| k.include?('referred_') }.
each_with_index{|(k, v), i| puts "index is #{i}. referred_email is #{v}" }
#=> index is 0. referred_email is theiremail1
#=> index is 1. referred_email is theiremail2
#=> index is 2. referred_email is theiremail3
答案 1 :(得分:0)
您提供的代码绝对没有错。如果我将以下输出粘贴到名为test.rb
的空白文件中:
params = {
"utf8"=>"✓",
"authenticity_token"=>"f7f0idqcQpXG/XzhQYCaEj3xQHLiQz1Nf1z9gF3CMxM=",
"referrer_email"=>"",
"referrer_name"=>"",
"referred_0"=>"theiremail1",
"referred_1"=>"theiremail2",
"referred_2"=>"theiremail3",
"commit"=>"SUBMIT"
}
@referred_emails = Array.new
@referred_emails = params.select{|k, v| k.start_with?('referred_') }.values
puts "referred emails array: " + @referred_emails.inspect.to_s
@referred_emails.each_with_index do |referred_email, index|
puts "index is #{index}. referred_email is #{referred_email}"
end
...然后我运行ruby test.rb
,我在Ruby 2.0 +上得到以下输出:
referred emails array: ["theiremail1", "theiremail2", "theiremail3"]
index is 0. referred_email is theiremail1
index is 1. referred_email is theiremail2
index is 2. referred_email is theiremail3
如果您的代码中存在错误,则不在您提供的代码示例中。