反正有没有找到Ruby数组中的下一个项目?
码:
# Find ALL languages
if !debug
lang = Language.all
else
lang = Language.where("id = ? OR id = ?", 22, 32)
end
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
lang.each do |l|
code = l.code.downcase
if File.exists?(file_path + code + ".yml")
File.delete(file_path + code + ".yml")
end
t1 = Time.now
info = {}
elements.each do |el|
unless l.id == 1
et = el.element_translations.where("language_id = ? AND complete = ?", l.id, true)
else
et = el.element_translations.where("language_id = ?", 1)
end
et.each do |tran|
info[code] ||= {}
info[code][el.human_readable] = tran.content.gsub("\n", "").force_encoding("UTF-8").encode!
end
end
File.open(file_path + code + ".yml", "w", :encoding => "UTF-8") do |f|
if f.write(info.to_yaml)
t2 = Time.now
puts code + ".yml File written"
puts "It took " + time_diff_milli(t1, t2).to_s + " seconds to complete"
# This is where I want to display the next item in the lang array
puts lang.shift(1).inspect
puts "*"*50
end
end
end
Run Code Online (Sandbox Code Playgroud)
Jac*_*kin 31
Array包括Enumerable,所以你可以使用each_with_index:
elements.each_with_index {|element, index|
next_element = elements[index+1]
do_something unless next_element.nil?
...
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*une 27
Enumerable如果您需要访问元素和下一个元素,那么迭代一个很好的方法是使用each_cons:
arr = [1, 2, 3]
arr.each_cons(2) do |element, next_element|
p "#{element} is followed by #{next_element}"
#...
end
# => "1 is followed by 2", "2 is followed by 3".
Run Code Online (Sandbox Code Playgroud)
正如Phrogz所指出的,Enumerable#each_cons可以在Ruby 1.8.7+中找到; 对于Ruby 1.8.6,你可以require 'backports/1.8.7/enumerable/each_cons'.
正如@Jacob指出的那样,另一种方法是使用each_with_index.
| 归档时间: |
|
| 查看次数: |
26111 次 |
| 最近记录: |