Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created October 10, 2010 19:57
Show Gist options
  • Save RyanScottLewis/619513 to your computer and use it in GitHub Desktop.
Save RyanScottLewis/619513 to your computer and use it in GitHub Desktop.
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