0

我是 Ruby 的新手,一般来说都是编程。我正在研究Ruby Koans。在卡住之前,我已经达到了 176/274。
这是“计分项目”,我需要编写一个方法来计算给定掷骰子的分数。
这可能不是你见过的最优雅的代码,但这是我想出的:

def score(dice)
  tally = 0
  tally += (dice.sort.to_s[/[1]+/].length % 3) * 100
  if dice.sort.to_s[/[1]+/].length >= 3
    tally += 1000
  end
  tally = tally + (dice.sort.to_s[/[5]+/].length % 3) * 50
  if dice.sort.to_s[/[5]+/].length >= 3
    tally += 500
  end
  if dice.sort.to_s[/[2]+/].length >= 3
    tally += 200
  end
  if dice.sort.to_s[/[3]+/].length >= 3
    tally += 300
  end
  if dice.sort.to_s[/[4]+/].length >= 3
    tally += 400
  end
  if dice.sort.to_s[/[6]+/].length >= 3
    tally += 600
  end
  return tally
end

第一个测试是:score([])需要返回0

当我运行它时,我得到“nil:NilClass 的未定义方法 `length'”(引用的行是 .length 的第一个实例)这告诉我“dice.sort.to_s[/[1]+/]”与“ score([])" 是 nil,但是当我在 irb>> 中运行它时,它是 0。

是什么赋予了?

4

2 回答 2

0

您使用的是哪个 Ruby 版本?我使用的是 1.9.2,我的 IRB 给了我同样的错误,因为如果没有匹配,正则表达式返回 nil。作为dice = []一个边界情况,您可以在代码的第一行添加一个检查,以便返回 0。

我今天做了 RubyKoans,尽管我的代码并不比你的漂亮,也许它会对你有所帮助:

def score(dice)

points = 0
dice.sort!
  nmbrs = Array.new
       dice.each { |n|
               nmbrs[n] = dice.select { |nm| nm == n}
       } 

 n = 0
 nmbrs.each { |vals|
      n = n + 1
      if(vals.nil?)
              next
      end
      if(vals.count >= 3)

              points += (n-1)*100 if (n-1) != 1
              points += 1000 if (n-1) == 1

              if vals.size > 3
                      if (n-1) == 1
                              points += 100 * (vals.size - 3)
                      else
                              if (n-1) == 5
                                      points += 50 * (vals.size - 3)
                            end
                      end

              end
      else
            points += 100 * (vals.count) if (n-1) == 1
            points += 50 * (vals.count) if (n-1) == 5
      end
   }

    points

 end

很抱歉这个糟糕的功能,但它确实有效,所以它可能会让你了解如何解决这个特定问题。

祝你好运!

于 2011-09-20T21:41:45.530 回答
0

好的。知道了。

非常抱歉,我说过运行“dice.sort.to_s[/[1]+/]”返回零而不是零,这一定是因为它有一些我不知道的存储值。当我运行“[].sort.to_s[/[1]+/]”时,它正确地返回了 nil。因此,我将每个 if 语句嵌套在一个检查中,以确保没有 nil 值。

def score(dice)
  tally = 0
  if dice.sort.to_s[/[1]+/]
    tally += (dice.sort.to_s[/[1]+/].length % 3) * 100
    if dice.sort.to_s[/[1]+/].length >= 3
      tally += 1000
    end
  end
  if dice.sort.to_s[/[5]+/]
    tally += (dice.sort.to_s[/[5]+/].length % 3) * 50
    if dice.sort.to_s[/[5]+/].length >= 3
      tally += 500
    end
  end
  if dice.sort.to_s[/[2]+/]
    if dice.sort.to_s[/[2]+/].length >= 3
      tally += 200
    end
  end
  if dice.sort.to_s[/[3]+/]
    if dice.sort.to_s[/[3]+/].length >= 3
      tally += 300
    end
  end
  if dice.sort.to_s[/[4]+/]
    if dice.sort.to_s[/[4]+/].length >= 3
      tally += 400
    end
  end
  if dice.sort.to_s[/[6]+/]
    if dice.sort.to_s[/[6]+/].length >= 3
      tally += 600
    end
  end
  return tally
end

所有测试通过。

于 2011-09-21T02:24:28.440 回答