From: Josh Cheek Date: 2012-02-09T17:05:17+09:00 Subject: Re: A better way implement "it" the ruby way --f46d044303f0ef8be804b88378c4 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Feb 8, 2012 at 10:36 AM, Bravo Man wrote: > > I am sure there are plenty of ways to implement this in Ruby more > clearly in a number of lines. It would be great if you could share your > ideas for the implementation. > > As others suggested, rand(...).to_s(...).rjust(...) is obviously the best way, but here is another option: 3.times.map { [*0..9,*'A'..'Z'].sample }.join 3.times will create an enumerator -- an object waiting to be invoked with a block that it will then call 3 times. Then we convert it to another enumerator with map, which, for each of the times, will invoke the block we give it and populate the result into an array. In the block, the 0..9 and 'A'..'Z' are ranges of digits and characters. Placing the splat in front of them turns them into arrays (note that in many places you have to surround this with parens, we don't here because we're in an array literal). Calling `sample` on this will choose one of its elements at random, and since this is the last expression in the block, it will be returned. All this so far gives us an array of size 3 with the digits and characters we want, we call `join` to turn them into a string. --f46d044303f0ef8be804b88378c4--