fabersky fabersky - 7 months ago 23
Ruby Question

Random zip method

Is there a way to use the

method in a random way?


If this is my code

['top', 'left', 'z-index'].zip(['5px', '35px', '10']).each do |attribute, value|
#not the actual code, just an example
puts "#{attribute} is #{value}"
end


It will print always in the same order:


top is 5px

left is 35px

z-index is 10


If I
shuffle
the arrays, then the elements will not match, so maybe it will print


left is 5px


and so on...

What I'd like to achieve is this, as I am using it in my
RSpec
tests:


FIRST RUN


top is 5px

left is 35px

z-index is 10


SECOND RUN


left is 35px

top is 5px

z-index is 10


etc.

Answer

What if you apply shuffle after zip?

['top', 'left', 'z-index'].zip(['5px', '35px', '10']).shuffle.each do |attribute, value|
  #not the actual code, just an example
  puts "#{attribute} is #{value}"
end

Every time you run this you'll get a different output. Sometimes this:

z-index is 10
left is 35px
top is 5px

And sometimes this:

left is 35px
z-index is 10
top is 5px

And sometimes other permutations of those same 3 lines