如何改进这个ruby代码和我对Hashes的使用?

mar*_*cgg 1 ruby ruby-on-rails

这里的要点是浏览数组docfiles并返回两个数组(temporary_file_pathstemporary_file_names).

我决定返回一个哈希,但我觉得我可以摆脱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
Run Code Online (Sandbox Code Playgroud)

Sim*_*tti 7

这里有很多解决方案.

返回双精度值.

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(...)
Run Code Online (Sandbox Code Playgroud)

使用收集.

def self.foobar(docfiles)
  docfiles.map do |docfile|
    File.exist?(docfile.path) ? [new_path, something_else] : nil
  end.compact
end

paths, names = Class.foo(...)
Run Code Online (Sandbox Code Playgroud)

使用注入(如果你想要一个哈希)

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
Run Code Online (Sandbox Code Playgroud)

上述所有解决方案都不会改变主方法逻辑.我不太喜欢使用数组/哈希而不是对象,因此当执行需要多次详细说明时,我通常最终会在对象中转换哈希值.

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
Run Code Online (Sandbox Code Playgroud)

另外,我不知道somethingelse 的含义,但是如果你可以从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
Run Code Online (Sandbox Code Playgroud)


Dou*_*ner 6

是的,只需使用它们而不是临时哈希:

def self.foobar(docfiles)
    temporary_information = { :file_paths => [], :file_names => [] }
    docfiles.each do |docfile|
      if File.exist? docfile.path
        temporary_information[:file_paths] << new_path
        temporary_information[:file_names] << something_else
      end
    end
    return temporary_information
end
Run Code Online (Sandbox Code Playgroud)