So basically for fun I was trying to generate a column of numbers (7 digits only 0s and 1s)
My code’s pretty short:
a = rand(0000000-1111111)
b = 220
a1 = rand(0000000-1111111)
a2 = rand(0000000-1111111)
a3 = rand(0000000-1111111)
a4 = rand(0000000-1111111)
a5 = rand(0000000-1111111)
while b !=0
puts a
puts a2
puts a3
puts a4
puts a5
end
My problem is that instead of generating a random column of 0s and 1s all the numbers are used.
Here’s idiomaticish Ruby:
Let’s unpack it:
5.times do...endis pretty self-explanatory. Do whatever’s betweendoandendfive times.(1..7)generates an array with seven elements. We don’t actually care what’s in it right now.mapreturns a new array where each element is the result of calling what’s between the braces. So seven times we’ll call[0, 1].sampleand squeeze the results into an array. Thesampleitself, of course, randomly picks either0or1. Finally.jointurns an array into a string. If we’d said.join('-'), for example, it’d put a hyphen between each element (1-0-0-1-1-1-0-1). But since we didn’t specify anything it puts nothing between each element (10011101).And there you have it.
As others have noted, for this particular problem it’s possible to do faster and shorter things by using binary. I don’t think this is the Ruby Way though. With respect to speed, “premature optimization is the root of all evil”, and if you have a violent aversion to slow code you shouldn’t be coding Ruby anyway. With regards to readability, that way may be shorter, but the above way is a lot clearer. “Oh, we’re doing something five times, and that’s going to be printing out a 7-thing long…random sequence of 0s and 1s…as a string”. It almost reads like English (if you know the word map (definition three)).