我有一个包含5个元素的散列,例如:
my_hash = {a: 'qwe', b: 'zcx', c: 'dss', d: 'ccc', e: 'www' }
我的目标是每次在循环哈希中返回,但没有一个元素,如:
my_hash = {a: 'qwe', b: 'zcx', c: 'dss', d: 'ccc' }
然后my_hash = {a: 'qwe', b: 'zcx', c: 'dss', e: 'www' }
等等
使用数组,我会使用组合方法,但当我使用哈希?
您可以将其转换为数组,稍后再将其转换回哈希:
my_hash.to_a.combination(4).to_a.sample.to_h
# => {:a=>"qwe", :b=>"zcx", :c=>"dss", :e=>"www"}
my_hash.to_a.combination(4).to_a.sample.to_h
# => {:a=>"qwe", :c=>"dss", :d=>"ccc", :e=>"www"}