【问题标题】:Finding similar values in a hash/array in Ruby在 Ruby 中的哈希/数组中查找相似值
【发布时间】:2015-07-23 17:24:15
【问题描述】:

我正在尝试计算一个“用户”与另一个用户有多少个“提示”。 这是我这样做的方法:

class User < ActiveRecord::Base
  has_many :tips, :inverse_of => :user
  ...
  public
  def tip_affinity_with(user)
    tipAffinity = 0

    user.tips.each do |tip|
      if self.tips.include?(tip)
        tipAffinity = tipAffinity + 1
      end
    end

    return tipAffinity
  end
end

我知道有些用户有他们都评价过的小费,但在我的表格中,所有用户的小费亲和度都是 0。

可能是什么问题?非常感谢任何帮助!


编辑:这是连接模型,Affinity

class Affinity < ActiveRecord::Base
  attr_accessible :user_A_id, :user_B_id, :tips_value, :tips_valid, :profile_value, :profile_valid, :value

  belongs_to :users
  belongs_to :inverse_user, :class_name => "Users"

  validates :tips_value, presence: true
  validates :profile_value, presence: true
  validates :user_A_id, presence: true
  validates :user_B_id, presence: true

  before_update :set_value
  before_create :set_value

  private
  def set_value
    self.value = 0.7*self.tips_value + 0.3*self.profile_value
    #self.value = PredictionConfigs.find(1)*self.tips_value + (1 - PredictionConfigs.find(1))*self.profile_value #Use prediction configs
  end
end

我确实在尝试找到两个哈希的交集。这两个哈希是两个用户的提示,一个是self,一个是user

再次感谢!

【问题讨论】:

  • 有关您的数据结构的更多信息将与此处相关。
  • 包含哪些内容会有帮助?
  • 用户如何与提示相关联?另外值得注意的是,在 Ruby 变量名中使用下划线,如 tip_affinity,最后一行的 return 语句是隐含的,可以省略。
  • 一个用户有_many 提示和一个提示有_many 用户。是这个意思吗?
  • 大概是这样,是的,但这似乎很奇怪。你不应该有很多这样的。您需要在中间有一个连接模型。

标签: arrays ruby ruby-on-rails-3 hash


【解决方案1】:

虽然这非常低效,但您可以尝试:

(user.tips & self.tips).length

如果您不使用模型中包含的数据,您确实希望避免加载模型。这应该可以仅使用数据库中存在的内容来计算。比如:

(user.tip_ids & self.tip_ids).length

【讨论】:

  • 我将它用于 if 语句。现在小费值不会每次都返回 0。但这究竟是做什么的呢?
  • 这会查找来自两个不同用户的提示之间的交集 (&amp;)。这假定两个用户创建的提示引用了相同的提示记录。如果没有,您可能需要做一些额外的工作。
【解决方案2】:

如果你的模型设置正确,这可以在数据库中完成:

def tip_affinity_with(user)
  user.tips.where(id: tip_ids).count
end

在我看来,根据 cmets(和您的示例代码),您的模型可能设置不正确。你有用户和提示之间的连接模型吗?比如:

class User < ActiveRecord::Base
  has_many :suggestions
  has_many :tips, through: :suggestions
end

class Suggestion < ActiveRecord::Base
  belongs_to :user
  belongs_to :tip
end

class Tip < ActiveRecord::Base
  has_many :suggestions
  has_many :users, through: :suggestions
end

看看你的Tip 模型会很有帮助。我的猜测是 Tip belongs_to :user 这就是为什么你没有得到用户之间的任何重叠,但我可能是错的。

这里有更多来自 has_many :through associations 上的 Rails 指南的阅读内容。

【讨论】:

  • 我愿意。这是亲和力模型。我会用它更新上面的帖子!
  • 请查看我上面的编辑,其中包含affinity 模型。
  • 我在您的 Affinity 课程中看不到与 tips 的任何联系。您只是忘记包含它,还是它不存在?
猜你喜欢
  • 2014-12-18
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 2011-04-15
相关资源
最近更新 更多