在Ruby中查找散列/数组中的类似值

时间:2015-05-12 17:23:59

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

我正在尝试计算“用户”与其他用户共有的“提示”数量。 这是我的方法:

if (Thread.CurrentThread.CurrentCulture.Name == "de-CH")
{
    // fix Windows 8.1 de-CH locale 
    Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
}

我知道有些用户有提示他们都有评价,但在我的表中,所有用户的tipAffinity为0。

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

编辑:这是联接模型,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

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

再次感谢!

2 个答案:

答案 0 :(得分:1)

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

(user.tips & self.tips).length

如果你不使用其中包含的数据,你真的想避免加载模型。这应该可以仅使用数据库中存在的内容进行计算。类似的东西:

(user.tip_ids & self.tip_ids).length

答案 1 :(得分:0)

如果您的模型设置正确,可以使用以下命令在数据库中完成:

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

在我看来,根据评论(和您的示例代码),您的模型可能无法正确设置。您是否有用户和提示之间的联接模型?类似的东西:

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指南的更多内容。