【问题标题】:Rubyiest way of setting value in array of hashes在哈希数组中设置值的 Rubyiest 方法
【发布时间】:2013-11-18 03:03:47
【问题描述】:

我有一个哈希数组,称为images,看起来像这样:

[{ area: 10, id: 39393, score: 10}, { area: 20, id: 33434, score: 5}, ...]

我想将每个对象的分数以百分比增加到最大区域。所以,这就是我现在的做法:

 max_area = images.max_by { |el| el["score"] }["area"]
    images.each do |image|
      if image["area"] > 0
        image["score"] += image["area"] / max_area
      end
    end

还有其他 Ruby 方法可以做到这一点吗?

【问题讨论】:

  • 我很喜欢你的...
  • Same here.. 如果几乎所有分数都大于零,则使用它可能会更好,除非,但现在我们在这里谈论品味。 image["score"] += (image["area"]/max_area) unless image["area"] <= 0
  • 我在考虑也许做一个地图,而不是 image.each...但是谢谢大家。
  • 你的看起来不错。 map 在这里会很丑。
  • 是的..我在@Linuxios

标签: ruby arrays hash enumerable


【解决方案1】:

“最红的”做事方式通常是使用对象。如果您不想创建成熟的课程,可以使用OpenStruct 开始。

require 'ostruct'

images = images.map { |image_hash| OpenStruct.new(image_hash) }
max_area = images.max_by(&:score).area

images.each do |image|
  if image.area > 0
    image.score += image.area / max_area
  end
end

但是,如果您的代码开始变得过于复杂,并且您愿意引入库,我建议您使用Virtus

require 'virtus'

class Image
  include Virtus.model

  attribute :area, Integer
  attribute :id, Integer
  attribute :score, Integer

  # You probably have more context to name this better
  def increment_score!(max_area)
    if area > 0
      self.score += area / max_area
    end
  end
end

class ImageCollection
  include Virtus.model

  attribute :images, Array[Image]

  # Win all the Enumerable methods for free
  include Enumerable
  def each(&block)
    images.each(&block)
  end

  def biggest_area
    image_with_best_score.area
  end

  def image_with_best_score
    images.max_by(&:score)
  end

  # You probably have more context to name this better
  def increment_scores!
    images.each { |image| image.increment_score!(biggest_area) }
  end
end

images = ImageCollection.new(images: [{ area: 10, id: 39393, score: 10}, { area: 20, id: 33434, score: 5}])
images.increment_scores!
puts images.map(&:score).join(", ") # => 11, 7

当然,如果您只是将一个脚本拼凑在一起,这是一个很大的过度杀伤力,但如果您的逻辑开始变得过于混乱,到处都是数组和散列,那么它可能具有巨大的价值。

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 2019-04-30
    • 2014-10-11
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2014-12-23
    • 2013-03-22
    相关资源
    最近更新 更多