ruby-on-rails - 我怎样才能改进这个 ruby​​ 代码和我对 Hashes 的使用?

标签 ruby-on-rails ruby

这里的重点是浏览数组 docfiles 并返回两个数组(temporary_file_pathstemporary_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/

相关文章:

javascript - rails partials 中的内联 Javascript

javascript - Angular.js 与 Ruby On Rails Forms 的集成

ruby-on-rails - (rails) 按网站上的点赞数排序

mysql - rails 服务器错误,mysql

ruby - 发出一个命令并运行多个 Ruby 文件

ruby - 创建空文件夹 S3 ruby​​ SDK

ruby-on-rails - helper 和包含在 Controller 中的区别是什么?

ruby-on-rails - 使用设计加密其他表列

ruby - 在文件中搜索字符串的最佳方法是什么?

ruby - 如何以编程方式一次运行多个 Rake 任务?