简体   繁体   English

Ruby函数编程的困惑—(入门)

[英]Ruby functional programming confusion — (Beginner)

I know I'm looping twice in the following code for no reason. 我知道我无缘无故地在以下代码中循环两次。 How could I go the following loop of records in one step instead of first selecting them and then performing actions on it. 我如何一步一步地执行以下记录循环,而不是先选择它们然后对其执行操作。

merchants = Merchant.all.select do |merchant|
  merchant.url.present? && merchant.url != merchant.new_data.url
end

merchants.each do |merchant|
  merchant.url = merchant.new_data.url
  merchant.save!
end

I bet it's something very simple -- I'm new to Ruby so all this is new to me. 我敢打赌,这很简单-我是Ruby的新手,所以这对我来说都是新的。

It's conceptually ok to iterate over data on separate steps (this allows modularization and composability). 从概念上讲,可以在单独的步骤上遍历数据(这样可以实现模块化和可组合性)。 Granted, this may be a bit inefficient when using strict structures (as opposed to lazy ones) like Ruby arrays, but no worries for small/medium arrays. 诚然,当使用像Ruby数组这样的严格结构(与惰性结构相对)时,这可能会有点效率低下,但对于中小型数组则不必担心。 Anyway, of course you can join the logic in one step, like this: 无论如何,您当然可以一步一步地加入逻辑,如下所示:

Merchant.all.each do |merchant|
  if merchant.url.present? && merchant.url != merchant.new_data.url
    merchant.url = merchant.new_data.url
    merchant.save!
  end
end

It will be quite inefficient doing Merchant.all when you have millions of rows, especially if they have many large fields. 当您有数百万行时,尤其是当它们具有许多大字段时,对Merchant.all将效率很低。 I would move the selection logic into the ActiveRecord query, something like this (untested): 我将选择逻辑移到ActiveRecord查询中,如下所示(未经测试):

Merchant.includes(:new_data).select(:url).where("url IS NOT NULL").where("url != new_data.url")

This will check for nil merchant url 这将检查零商家网址

merchants.each do |merchant|
  merchant.url = merchant.url || merchant.new_data.url
  merchant.save!
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM