Ruby在数组中找到下一个
反正有没有找到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
Array
包含Enumerable
,因此您可以使用each_with_index
:
elements.each_with_index {|element, index| next_element = elements[index+1] do_something unless next_element.nil? ... }
如果您需要访问元素和下一个元素,则迭代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".
正如Phrogz所指出的,可以在Ruby 1.8.7+中使用Enumerable#each_cons
each_cons; 对于Ruby 1.8.6,您可以require 'backports/1.8.7/enumerable/each_cons'
。
正如@Jacob指出的那样,另一种方法是使用each_with_index
。
arr[n..-1].find_index(obj) + n
根据Marc-Andrés的好回答,我想提供一个答案,以通用的方式,通过使用nil
填充为所有元素提供以下元素,也是最后一个元素:
arr = [1, 2, 3] [arr, nil].flatten.each_cons(2) do |element, next_element| p "#{element} is followed by #{next_element || 'nil'}" end # "1 is followed by 2" # "2 is followed by 3" # "3 is followed by nil"
现在,在我们处理它的同时,我们还可以为所有元素提供前面的元素:
arr = [1, 2, 3] [nil, arr, nil].flatten.each_cons(3) do |prev_element, element, next_element| p "#{element} is preceded by #{prev_element || 'nil'} and followed by #{next_element || 'nil'}" end # "1 is preceded by nil and followed by 2" # "2 is preceded by 1 and followed by 3" # "3 is preceded by 2 and followed by nil"