Created
October 10, 2010 19:57
-
-
Save RyanScottLewis/619513 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def token(size=6) | |
chars = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a | |
chars.sample(size).inject("") { |result, char| result << char } | |
end | |
p token # => "aN7drK" | |
p token # => "tVO3HG" | |
p token(8) # => "UqeYGPL2" | |
=begin | |
If you look at the ASCII table, then you can see why I used 3 different ranges. | |
Array#sample grabs a random element from the array and when you give it an integer as an argument, then it will gram that many random elements. | |
Array#inject is the tricky part. It takes an object as an argument. It works just like Array#each, only it passes along your argument to the block and returns it. In the above example, I gave the inject block a new String instance and added each char to it. Since ruby returns the last thing evaluated in the method, then it will return the "injected" string. | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment