Skip to content

Instantly share code, notes, and snippets.

@avocado3
Created March 6, 2014 03:45
Show Gist options
  • Save avocado3/9381957 to your computer and use it in GitHub Desktop.
Save avocado3/9381957 to your computer and use it in GitHub Desktop.
Generating random strings in Ruby
#!/usr/local/bin/ruby
# coding: utf-8
require 'securerandom'
def rand_str(chars, length)
length.times.map {
chars[SecureRandom.random_number(chars.length)]
}.join('')
end
if $0 == __FILE__
require 'optparse'
option = OptionParser.new
chars = []
length = 20
specified = 1
option.on('-A', '--capltal-alphabets') { |opt| chars.concat ('A'..'Z').to_a if opt }
option.on('-a', '--small-alphabets') { |opt| chars.concat ('a'..'z').to_a if opt }
option.on('-n', '--numeric') { |opt| chars.concat ('0'..'9').to_a if opt }
option.on('-h', '--hiragana') { |opt| chars.concat ('あ'..'ん').to_a if opt }
option.on('-k', '--katakana') { |opt| chars.concat ('ア'..'ン').to_a if opt }
option.on('-p', '--printable') { |opt| chars.concat ('!'..'~').to_a if opt }
option.on('-l LENGTH', '--length=LENGTH') { |val| length = val.to_i if val }
option.on('-t TIMES', '--times=TIMES') { |val| specified = val.to_i if val }
option.parse ARGV
chars = ('!'..'~').to_a if chars.empty?
specified.times { puts rand_str(chars, length) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment