Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Last active September 2, 2019 20:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KamilLelonek/4d9b4339dfa07c34830e to your computer and use it in GitHub Desktop.
Save KamilLelonek/4d9b4339dfa07c34830e to your computer and use it in GitHub Desktop.
Ruby random string generator with particular length
class RandomStringGenerator
def without_numbers(length)
random_string(length, alphabet)
end
def with_numbers(length)
random_string(length, alphabet + numbers)
end
private
def random_string(length, charset)
Array.new(length) { charset.sample }.join
end
def alphabet
@alphabet ||= Array('A'..'Z') + Array('a'..'z')
end
def numbers
@numbers ||= Array(0 .. 9)
end
end
@KamilLelonek
Copy link
Author

➜  ~  pry
[1] (pry) main: 0> class RandomStringGenerator
[1] (pry) main: 0*   def without_numbers(length)
[1] (pry) main: 0*     random_string(length, alphabet)
[1] (pry) main: 0*   end
[1] (pry) main: 0*
[1] (pry) main: 0*   def with_numbers(length)
[1] (pry) main: 0*     random_string(length, alphabet + numbers)
[1] (pry) main: 0*   end
[1] (pry) main: 0*
[1] (pry) main: 0*   private
[1] (pry) main: 0*   def random_string(length, charset)
[1] (pry) main: 0*     Array.new(length) { charset.sample }.flatten.join
[1] (pry) main: 0*   end
[1] (pry) main: 0*
[1] (pry) main: 0*   def alphabet
[1] (pry) main: 0*     @alphabet ||= Array('A'..'Z') + Array('a'..'z')
[1] (pry) main: 0*   end
[1] (pry) main: 0*
[1] (pry) main: 0*   def numbers
[1] (pry) main: 0*     @numbers ||= Array(0 .. 9)
[1] (pry) main: 0*   end
[1] (pry) main: 0* end
[3] (pry) main: 0>
[4] (pry) main: 0> RandomStringGenerator.new.with_numbers(4)
=> "44sl"
[5] (pry) main: 0> RandomStringGenerator.new.without_numbers(4)
=> "CeNl"

@lym
Copy link

lym commented Sep 2, 2019

Nice and easy. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment