Created
March 6, 2014 03:45
-
-
Save avocado3/9381957 to your computer and use it in GitHub Desktop.
Generating random strings in Ruby
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
#!/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