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

我正在研究Ruby Koans(Ruby的教程项目)。 在About_Dice_Project中 ,需要创建一个名为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 

关于它的想法:

如果辊是随机的,则可能(尽管不太可能)两个连续的辊相等。 什么是更好的测试方法?

我的想法是使用assert_not_equal first_time.object_id, second_time.object_id测试assert_not_equal first_time.object_id, second_time.object_idsecond_timeobject_id 。 它有效,但我是对的吗? 作为Ruby和编程的初学者,究竟什么是object_id ? 顺便说一句,是否有可能在降价中certificate文本的合理性?

任何帮助将不胜感激 !

object_ids和相等

您不应该比较object_id ,而是比较value s。

 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