Ruby Koans 182.重构帮助

标签 ruby

你能帮我重构我为 Ruby Koans #182 提出的解决方案吗?这是您在其中编写得分方法来计算贪婪游戏分数的公案。以下代码有效,所有测试均通过。

但是,它感觉又长又不像 ruby 。我怎样才能让它变得更好?

def score(dice)
rollGreedRoll = Hash.new
rollRollCount = Hash.new
(1..6).each do |roll|
    rollGreedRoll[roll] = roll == 1 ? GreedRoll.new(1000, 100) :
            GreedRoll.new(  100 * roll, roll == 5 ? 50 : 0)
    rollRollCount[roll] = dice.count { |a| a == roll }
end


  score =0 


  rollRollCount.each_pair do |roll, rollCount|
    gr = rollGreedRoll[roll]  
    if rollCount < 3
        score += rollCount * gr.individualPoints
    else
        score += gr.triplePoints + ((rollCount - 3) * gr.individualPoints)

    end 
  end

  return score
end

class GreedRoll
    attr_accessor :triplePoints
    attr_accessor :individualPoints

    def initialize(triplePoints, individualPoints)
        @triplePoints = triplePoints
        @individualPoints = individualPoints
    end
end

最佳答案

我在 https://gist.github.com/1091265 上发布了重构演练。 .最终解决方案如下所示:

def score(dice)
  (1..6).collect do |roll|
    roll_count = dice.count(roll)
    case roll
      when 1 : 1000 * (roll_count / 3) + 100 * (roll_count % 3)
      when 5 : 500 * (roll_count / 3) + 50 * (roll_count % 3)
      else 100 * roll * (roll_count / 3)
    end
  end.reduce(0) {|sum, n| sum + n}
end

注意: .reduce.inject

的同义词

关于Ruby Koans 182.重构帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738715/

相关文章:

ruby-on-rails - rails ruby​​ 遍历目录中的部分

ruby - RSpec NoMethodError : "undefined method ` describe' for main Object"

arrays - 组合数组并对整数求和

ruby-on-rails - 你如何在 Rails 中做相对时间?

ruby - 如何将用户输入与 Ruby 中散列中的键/值对进行比较?

ruby - 如何使用 google-api-ads-ruby gem 添加排除关键字和网络搜索参数?

ruby - 你如何用 Mongoid 编写 "(A OR B) AND (A OR C)"查询?

ruby - 从文件中读取变量并替换

ruby - config.rb 和页面中的中间人变量可见性

ruby - 如何使用 Haml 插入带有动态内容的 HTML 注释?