Ruby 从两个单独的哈希键迭代哈希值的最有效方法

Ruby 从两个单独的哈希键迭代哈希值的最有效方法,ruby,Ruby,我有散列值: my_hash = {"host_names"=>["batman", "robin"], "files"=>["file1", "file2", "file3"]} 我需要迭代每个主机名,然后从每个主机中提取相同的日志 除: my_hash.each do |k, v| k["host_names].each do |hostname| k["log"].each do |log| get_log_file(host, log) en

我有散列值:

my_hash = {"host_names"=>["batman", "robin"], "files"=>["file1", "file2", "file3"]}
我需要迭代每个主机名,然后从每个主机中提取相同的日志

除:

my_hash.each do |k, v|
  k["host_names].each do |hostname|
    k["log"].each do |log|
      get_log_file(host, log)
    end
  end
end
有没有更有效的方法


提前谢谢你。

我不明白你为什么要在散列的键上迭代,然后在每个键上调用[“something”]。这似乎是错误的

    hostnames = my_hash["host_names"]
    files = my_hash["files"]

    hostnames.each do |hostname|
         files.each do |file|
             get_log_file host, file
         end
    end

我不明白为什么要迭代散列的键,然后对每个键调用[“something”]。这似乎是错误的

    hostnames = my_hash["host_names"]
    files = my_hash["files"]

    hostnames.each do |hostname|
         files.each do |file|
             get_log_file host, file
         end
    end

首先,你可以去掉外环:

my_hash['host_names'].each do |host|
  my_hash['files'].each do |file|
    get_log_file(host, file)
  end
end

它实际上没有效率更高,但更干净一点。我认为不管怎样,这将是两个循环。

好吧,首先,你可以去掉外循环:

my_hash['host_names'].each do |host|
  my_hash['files'].each do |file|
    get_log_file(host, file)
  end
end

它实际上没有效率更高,但更干净一点。我认为这将是两个循环。你可以这样做:

my_hash = {"host_names"=>["batman", "robin"],
           "files"=>["file1", "file2", "file3"]}

def get_log_file(h,f)
  puts "processing file #{f} for #{h}"
end

my_hash["host_names"].product(my_hash["files"]).each {|h,f| get_log_file(h, f)}
  #=>  processing file file1 for batman
  #    processing file file2 for batman
  #    processing file file3 for batman
  #    processing file file1 for robin
  #    processing file file2 for robin
  #    processing file file3 for robin

你可以这样做:

my_hash = {"host_names"=>["batman", "robin"],
           "files"=>["file1", "file2", "file3"]}

def get_log_file(h,f)
  puts "processing file #{f} for #{h}"
end

my_hash["host_names"].product(my_hash["files"]).each {|h,f| get_log_file(h, f)}
  #=>  processing file file1 for batman
  #    processing file file2 for batman
  #    processing file file3 for batman
  #    processing file file1 for robin
  #    processing file file2 for robin
  #    processing file file3 for robin

当您问“有没有更有效的方法来实现这一点?”时,您的问题就变成了堆栈溢出的非主题,而变成了的主题。您的代码在语法上是无效的。是。。我错过了一些关于逻辑的东西,但是我希望我仍然能够推广总体思路。@Tin Man,我没有发送到代码审阅的原因是因为这不是我使用的实际逻辑,只是程序的一个摘录。我觉得这更像是一个如何去做的问题。我同意我用了蹩脚的措辞。对此很抱歉。当您问“有没有更有效的方法来执行此操作?”时,您的问题会成为堆栈溢出的非主题,而成为的主题。您的代码在语法上无效。是。。我错过了一些关于逻辑的东西,但是我希望我仍然能够推广总体思路。@Tin Man,我没有发送到代码审阅的原因是因为这不是我使用的实际逻辑,只是程序的一个摘录。我觉得这更像是一个如何去做的问题。我同意我用了蹩脚的措辞。对不起,对不起。。示例中没有提到另一层。有一个外层表示主机的类型(web、db等)。然后我指定主机和日志。这两个系统的日志都是通用的。抱歉。。示例中没有提到另一层。有一个外层表示主机的类型(web、db等)。然后我指定主机和日志。这两个系统都有相同的日志。感谢您的反馈。感谢您的反馈。