我可能会带着这个去一点点。
我正在使用Cucumber Capybara和Ruby,我想创建一些特定数据的哈希值,然后让我的测试随机选择其中一个哈希值。可以这样做吗?
我的方法包含哈希:
def random_vehicles
a1 = {:vrm => 'A1',
:id => '11111111111',
:post_code => 'AA11AA'
}
b1 = {:vrm => 'B1',
:id => '22222222222',
:post_code => 'BB11BB'
}
end
如何在该方法中随机选择两个哈希值中的一个?如:
sample = random_vehicles.sample # This doesn't work
由于
答案 0 :(得分:3)
尝试
def random_vehicles
a1 = {:vrm => 'A1',
:id => '11111111111',
:post_code => 'AA11AA'
}
b1 = {:vrm => 'B1',
:id => '22222222222',
:post_code => 'BB11BB'
}
[a1, b1]
end
vehicles = random_vehicles
p vehicles.sample
答案 1 :(得分:2)
以下是如何修改方法以使您的初始random_vehicles.sample
正常工作:
def random_vehicles
[
{:vrm => 'A1',
:id => '11111111111',
:post_code => 'AA11AA'
},
{:vrm => 'B1',
:id => '22222222222',
:post_code => 'BB11BB'
}
]
end
random_vehicles.sample
#=> {:vrm=>"B1", :id=>"22222222222", :post_code=>"BB11BB"}
random_vehicles.sample
#=> {:vrm=>"A1", :id=>"11111111111", :post_code=>"AA11AA"}
请注意,方法名称很重要:它取决于您实际希望方法返回的内容。在这种情况下,方法名称是sample_vehicles
(复数),所以它感觉很自然,它返回一个对象集合。
如果您需要它已经返回车辆,那么您应该更改方法并重命名:
def random_vehicle
[
{:vrm => 'A1',
:id => '11111111111',
:post_code => 'AA11AA'
},
{:vrm => 'B1',
:id => '22222222222',
:post_code => 'BB11BB'
}
].sample
end
random_vehicle
#=> {:vrm=>"B1", :id=>"22222222222", :post_code=>"BB11BB"}
random_vehicle
#=> {:vrm=>"B1", :id=>"22222222222", :post_code=>"BB11BB"}
random_vehicle
#=> {:vrm=>"A1", :id=>"11111111111", :post_code=>"AA11AA"}