Ready to Start Your Career?

Simple String Manipulation in Ruby, Via Password Generator

rchamblee 's profile image

By: rchamblee

August 22, 2017

Ruby is a small, simple, yet powerful language used primarily for web development in the form of Ruby on Rails. What I'm going to present here, however, is a very simple ruby 'script' for generating passwords that I cooked up in a few minutes. For those interested in Ruby, there will be a line-by-line breakdown of the code, and for those who simply want to generate a password for themselves, you can run the script here.letters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"Here, we define a string 'letters' that we just filled with every variation of all the letters in the alphabet.numbers = "1234567890"The same thing we did with letters, just with numbers.symbols = "~`!@#$%^&*()-_+=;:/?.,><"et cetera.Now, let's define some variables that allow us to check if the user wants to include certain types.use_letters = FALSEuse_numbers = FALSEuse_symbols = FALSE Get the desired length of the password using gets.chomp and converting it to an integer with .to_iprint "What length would you like the password to be?n"pass_length = gets.chomp.to_i Check if the user wants to include letters, forcing their response to be upper case for sanity reasons, and setting the use_letters boolean we defined earlier to TRUE if they desire to use letters.print "Use Letters? (Y/N)n"lResponse = gets.chomp.upcaseif lResponse == "Y"use_letters = TRUEend Doing the same here that we did with letters, but for numbers.print "Use Numbers? (Y/N) n"nResponse = gets.chomp.upcaseif nResponse == "Y"use_numbers = TRUEend And again for symbols.print "Use Symbols? (Y/N)n"sResponse = gets.chomp.upcaseif sResponse == "Y"use_symbols = TRUEend Conditionally include the various strings into the concatenated "pass_string".  Inline conditionals like this take the format of (conditional ? if true : if false)pass_string = (use_letters ? letters : "") + (use_numbers ? numbers : "") + (use_symbols ? symbols : "")Here we split the string into an array to allow us to scramble the elements around using Ruby's built in ".shuffle". We do it twice here for redundancy only. The .join method then takes the elements of the array and concatenates them all into a single string.pass_string = pass_string.split("")pass_string = pass_string.shuffle.shuffle.joinNext, we check if the length of the password is greater than the one desired, and if it is, we take a substring of the desired length and print that instead, otherwise printing the entire password string. To get a substring in ruby, simply take your string variable (here, pass_length) and append [0...(desired length)]print ((pass_string.length > pass_length) ? pass_string[0...pass_length] : pass_string)
Schedule Demo