Ruby Koans:测试两组具有相同值的不同骰子

Ruby Koans : Test two different sets of dices who have same values

我正在研究 Ruby Koans(Ruby 的教程项目)。在About_Dice_Project中,要求创建一个class,名称为DiceSet。我成功了,但是有一个有趣的问题。

代码如下:

class DiceSet

  # Attribute reader
  attr_reader :values

  # Initializer
  def initialize
    @values = []
  end

  # Roll method
  def roll(dice_amount)
    @values = Array.new(dice_amount) { rand(1..6) }
  end
end

这个测试很有趣:

def test_dice_values_should_change_between_rolls
    dice = DiceSet.new

    dice.roll(5)
    first_time = dice.values

    dice.roll(5)
    second_time = dice.values

    assert_not_equal first_time, second_time,
      "Two rolls should not be equal"
  end

THINK ABOUT IT:

If the rolls are random, then it is possible (although not likely) that two consecutive rolls are equal. What would be a better way to test this?

我的想法是测试 first_timesecond_timeobject_id,使用 assert_not_equal first_time.object_id, second_time.object_id。它有效,但我是对的吗?作为 Ruby 和编程的初学者,object_id 到底是什么? 顺便说一下,是否可以在 markdown 中证明文本的合理性?

任何帮助将不胜感激!

object_ids 和相等

你不应该比较 object_ids,而是 values。

a = [1, 2, 3]
b = [1, 2, 3]

puts a == b
#=> true
puts a.object_id == b.object_id
#=> false

通过比较 object_id,您可以测试变量是否引用完全相同的对象。在您的情况下, first_timesecond_time 是彼此独立创建的,因此它们不能引用同一个对象。不过,它们可以具有相同的值。

想一想

确保没有两个连续的掷骰是相等的一种方法是使用 while 循环:

class DiceSet
  # Attribute reader
  attr_reader :values

  # Initializer
  def initialize
    @values = []
    @last_values = []
  end

  # Roll method
  def roll(dice_amount)
    while @values == @last_values
      @values = Array.new(dice_amount) { rand(1..6) }
    end
    @last_values = @values
    @values
  end
end

dice = DiceSet.new

dice.roll(5)
first_time = dice.values

dice.roll(5)
second_time = dice.values # <-- cannot be equal to first_time