Ruby在数组中找到下一个

时间:2011-01-04 17:25:37

标签: ruby arrays

有没有找到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

5 个答案:

答案 0 :(得分:31)

Array包含Enumerable,因此您可以使用each_with_index

elements.each_with_index {|element, index|
   next_element = elements[index+1]
   do_something unless next_element.nil?
   ...

}

答案 1 :(得分: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".

正如Phrogz所指出的,Enumerable#each_cons可用于Ruby 1.8.7+;对于Ruby 1.8.6,您可以require 'backports/1.8.7/enumerable/each_cons'

正如@Jacob指出的那样,另一种方法是使用each_with_index

答案 2 :(得分:4)

arr[n..-1].find_index(obj) + n

答案 3 :(得分:2)

根据Marc-Andrés的好回答,我希望提供一个答案,以通用的方式,通过用{{1}填充为所有元素提供以下元素,也是最后一个元素}:

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"

答案 4 :(得分:1)

foo = ["alpha", "beta", "gamma", "delta"]
foo[foo.find_index("beta") + 1]