Ruby 我们能把这两个循环结合起来,使它们并行运行吗?
查找以下代码:Ruby 我们能把这两个循环结合起来,使它们并行运行吗?,ruby,Ruby,查找以下代码: 我们可以将这两个循环组合起来,使它们并行运行吗? 前提是两个循环计数相同 我想创建散列,其中键将是文本,而项将是 href 您可以使用来执行此操作: returned_hash = {} all_links.zip(all_attachment_names) do |link, name| returned_hash[name.text] = link.attribute("href").strip end 您还可以通过使用映射提取href和文本,以函数式编程方式执行此操作
循环计数
相同散列
,其中键将是文本
,而项将是
href
returned_hash = {}
all_links.zip(all_attachment_names) do |link, name|
returned_hash[name.text] = link.attribute("href").strip
end
您还可以通过使用映射
提取href
和文本
,以函数式编程方式执行此操作:
hrefs = all_links.map{|link| link.attribute("href").strip}
names = all_attachment_names.map{|name| name.text}
returned_hash = Hash[names.zip(hrefs)]
这样做(可以说)更美观,但效率稍低,因为它需要两倍的迭代次数,并创建两个额外的数组,但除非你有大量的链接,否则这不会成为问题。为什么不
散列[all\u links.zip(all\u attachment\u names)]
?因为您需要从数组项中提取文本
和href
属性,然后添加2个映射。我更喜欢函数式编程:D@AndyH完美,因为您还处理了href
和文本<代码>+1
给你@ŁukaszNiemier是的,很公平。你的解决方案也是我的第一反应:)我会把它作为我答案的补充。为什么不把[all_links.zip(all_attachment_names)]?@ukaszNiemier,因为我不知道Hash:[]
。谁开始了这么糟糕的向下投票游戏?
returned_hash = {}
all_links.zip(all_attachment_names) do |link, name|
returned_hash[name.text] = link.attribute("href").strip
end
hrefs = all_links.map{|link| link.attribute("href").strip}
names = all_attachment_names.map{|name| name.text}
returned_hash = Hash[names.zip(hrefs)]