【发布时间】: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
我的代码的精确编辑:
external 是 shopify 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