这里的重点是浏览数组 docfiles
并返回两个数组(temporary_file_paths
和 temporary_file_names
)。
我决定返回一个 Hash,但我觉得我可以摆脱 2 个临时数组,但我不确定如何......
def self.foobar docfiles
temporary_information = Hash.new
temporary_file_paths = []
temporary_file_names = []
docfiles.each do |docfile|
if File.exist? docfile.path
temporary_file_paths << "new_path"
temporary_file_names << "something_else"
end
end
temporary_information[:file_paths] = temporary_file_paths
temporary_information[:file_names] = temporary_file_names
return temporary_information
end
最佳答案
这里有大量的解决方案。
返回 double 值。
def self.foobar(docfiles)
temporary_file_paths = []
temporary_file_names = []
docfiles.each do |docfile|
if File.exist? docfile.path
temporary_file_paths << new_path
temporary_file_names << something_else
end
end
[temporary_file_paths, temporary_file_names]
end
paths, names = Class.foo(...)
使用收集。
def self.foobar(docfiles)
docfiles.map do |docfile|
File.exist?(docfile.path) ? [new_path, something_else] : nil
end.compact
end
paths, names = Class.foo(...)
使用注入(inject)(如果你想要哈希)
def self.foobar(docfiles)
docfiles.inject({ :file_paths => [], :file_names => []}) do |all, docfile|
if File.exist?(docfile.path)
all[:file_paths] << new_path
all[:file_names] << something_else
end
all
end
end
以上所有方案都没有改变主方法逻辑。 我不太喜欢使用数组/散列而不是对象,所以当执行需要多次详细说明时,我通常最终会在对象中转换散列。
TemporaryFile = Struct.new(:path, :something_else)
def self.foobar docfiles
docfiles.map do |docfile|
if File.exist?(docfile.path)
TemporaryFile.new(new_path, something_else)
end
end.compact
end
此外,我不知道 something
else 的含义,但如果它是您可以从 new_path 获得的东西,那么您可以使用惰性执行。
TemporaryFile = Struct.new(:path) do
def something_else
# ...
end
end
def self.foobar docfiles
docfiles.map do |docfile|
TemporaryFile.new(new_path) if File.exist?(docfile.path)
end.compact
end
关于ruby-on-rails - 我怎样才能改进这个 ruby 代码和我对 Hashes 的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1940894/