Ruby Koans:测试两组具有相同值的不同骰子 [英] Ruby Koans : Test two different sets of dices who have same values
问题描述
我正在研究Ruby Koans(Ruby的一个教程项目).在 About_Dice_Project 中,需要创建一个名为 DiceSet 的类.我成功了,但是有一个有趣的问题.
I am working through the Ruby Koans(A tutorial project of Ruby). In the About_Dice_Project, it's demanded to create a class named DiceSet. I succeed, but there is a interesting question.
这是代码:
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_time
和second_time
的 object_id
assert_not_equal first_time.object_id, second_time.object_id
.可以,但是我是对的吗?作为Ruby和编程的初学者,object_id
的确是什么?
顺便说一句,是否有可能在markdown中证明文本的正确性?
My idea is to test the object_id of first_time
and second_time
, using
assert_not_equal first_time.object_id, second_time.object_id
. It works but am i right ? As a beginner in Ruby and programming, what is an object_id
indeed ?
By the way, is it possible to justify the text in markdown ?
任何帮助将不胜感激!
推荐答案
object_ids和相等性
您不应该比较object_id
,而应该比较value
.
a = [1, 2, 3]
b = [1, 2, 3]
puts a == b
#=> true
puts a.object_id == b.object_id
#=> false
通过比较object_id
,您正在测试变量是否指向完全相同的对象.在您的情况下,first_time
和second_time
是彼此独立创建的,因此它们不能引用同一对象.它们可以具有相同的值.
By comparing object_id
s, you're testing if variables refer to the exact same object. In your case, first_time
and second_time
are created independently from each others, so they cannot reference the same object. They can have the same values, though.
一种确保两个连续掷骰不相等的方法是使用while
循环:
One way to ensure that no two consecutive rolls are equal would be to use a while
loop :
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
这篇关于Ruby Koans:测试两组具有相同值的不同骰子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!