红宝石在寻找下一个数组 [英] Ruby find next in array
本文介绍了红宝石在寻找下一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
反正有没有找到一个Ruby数组的下一个项目?
code:
#查找所有语言
如果!调试
LANG = Language.all
其他
LANG = Language.where(ID =?或ID =?,22,32)
结束#所有的元素
元素= Element.where(human_readable IS NOT NULL)lang.each做| L |
code = 1。code.downcase
如果File.exists?(FILE_PATH + code +.yml)
File.delete(FILE_PATH + code +.yml)
结束 T1 = Time.now 信息= {}
elements.each做|埃尔|
除非l.id == 1
等= el.element_translations.where(LANGUAGE_ID =?AND完整=?,l.id,真)
其他
等= el.element_translations.where(LANGUAGE_ID =?,1)
结束
et.each做| TRAN |
信息[code] || = {}
信息[code] [el.human_readable] = tran.content.gsub(\\ n,).force_encoding(UTF-8)。恩code!
结束
结束
File.open(FILE_PATH + code +.yml,W:编码=>中UTF-8)做| F |
如果f.write(info.to_yaml)
T2 = Time.now 把code +.yml文件写入
把花+ time_diff_milli(T1,T2).to_s +秒即可完成
#这就是我想要的郎阵列中显示的下一个项目
放lang.shift(1).inspect
把** 50
结束
结束
结束
解决方案
阵列
包括可枚举
,这样你就可以使用<一个href=\"http://www.ruby-doc.org/core/classes/Enumerable.html#M003137\"><$c$c>each_with_index$c$c>:
elements.each_with_index {|元素,指数|
next_element =元素[索引+ 1]
do_something如果next_element.nil?
...}
Is there anyway to find the next item in a Ruby Array?
Code:
# 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
includes Enumerable
, so you can use each_with_index
:
elements.each_with_index {|element, index|
next_element = elements[index+1]
do_something if next_element.nil?
...
}
这篇关于红宝石在寻找下一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文