【问题标题】:Run code if x times if item present如果项目存在,则运行代码 x 次
【发布时间】:2016-09-01 13:07:08
【问题描述】:

从我的last question,我似乎无法得到我想要的东西。下面解释得更好:

external = ["apple"]
internal = ["grapes", "pear", "mangoes", "apple"]

external.each do |fruit|
 if not internal.include?("apple") # fruit will be in place of apple.
   puts "yes"
   # run code
 end
end

到目前为止,这是打印一次。如何让它打印三遍?在英语中,我说如果apple 存在,请不要理会apple,给我其他人,然后运行下面的代码。如果有 4 项,其中一项是 apple,则运行代码 3 次。如果apple 不存在,则运行代码 4 次。

我希望这很清楚。谢谢

我需要 100% 准确

内部是一个模型(postgres) 外部是shopify api(数组)

我已将 shopify 的产品 ID 保存在我的数据库 Bar 的一个名为 foo 的列中。 Bar.first.foo 给了我 shopify 的 ID。 Bar 将有其他带有/不带有 shopify id 的对象。所以如果有shopify,剩下的给我。这就是我想出的原因:

external.each do |fruit|
 if not internal.include?("apple") # fruit will be in place of apple.
   puts "yes"
   # run code
 end
end

我的代码的精确编辑:

externalshopify product response

external = # shopify's response (forget about the above example).
internal = Product.all # All of the user's products

所以在我的产品模型中,我有一个产品 ID。该 ID 用于 shopify 产品。示例:

Product.first.product_id = # "8cd66767sssxxxxx"

在同一个模型(产品)中,我有更多对象以及 shopify 产品 ID。我需要除 id 8cd66767sssxxxxx 之外的所有对象:

Product.last.product_id = # "BOOK" etc but not a shopify id.

fl00r 的答案在我的控制台中有效,但在控制器中无效。奇怪的。这对我有用。

external.each do |e|
  internal.each do |i|
    puts i.product_id unless i.product_id == e.id.to_s
  end
end

小问题。在第一次迭代中,id 被包括在内,但在第二次迭代中不包括在内。不知道从这里做什么。

【问题讨论】:

  • (内部-外部).each { |fruit| puts 'yes' #你的代码 }
  • 那么输出是什么?
  • @fl00r <Product:0x007fea45101da0> x13(如果是数组)。我期待 x12。
  • 您正在遍历一个包含 1 个元素的列表。预期的输出应该是空的。我完全糊涂了。 external.each 将只有一次迭代。并且它将省略苹果在内部列表中提供的任何输出。
  • 我要去看看我的代码是否有问题。另外,我可能不太清楚。稍后我将使用我的代码副本进行更新。谢谢。

标签: ruby-on-rails ruby postgresql ruby-on-rails-5


【解决方案1】:

你为什么不这样做呢?

(internal - external).each do |fruit| 
  puts 'yes' 
  #your code
end

【讨论】:

  • 对不起,我可能不太清楚。这是一个简化示例的数组对象。 external 是一个 api 对象,而 internal 是我的本地数据库。
【解决方案2】:

另一种方法是重新考虑您的外部数据结构。 Set 更适合这里(不过我们将使用 Hash):

external = ["apple"]
internal = ["grapes", "pear", "mangoes", "apple"]

external_hash = external.each_with_object({}){ |o, h| h[o] = true }

internal.each do |item|
  unless external_hash[item]
    p item
  end
end
#=> "grapes"
#=> "pear"
#=> "mangoes"

或者你可以先过滤你的内部列表

internal_filtered = internal.reject{ |item| external_hash[item] }
internal_filtered.each do |item|
  p item
end
#=> "grapes"
#=> "pear"
#=> "mangoes"

Array 转换为Hash 将花费您O(n),并且每次后续查找将花费O(1) 摊销。

所以总复杂度为O(n+m),其中n 是外部列表的大小,m 是内部列表的大小。

【讨论】:

  • 我不需要苹果。我需要避开苹果并得到其余的。
  • @Sylar 做虎钳然后 :)
  • 好的...让我看看。
  • 我还在获取所有内部信息。
  • 也许你混淆了each 的输出和你真正的块执行输出?因为each 会输出原始的internal 数组,但你应该忽略它。
猜你喜欢
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
相关资源
最近更新 更多