[Ruby] How to generate a random alphabet string

Introduction

・ It is a memorandum of knowledge caught up. ・ I would appreciate it if you could point out any mistakes.

This keyword

To_a method

A method to convert hashes, range objects, etc. into arrays. Source: [Ruby] Let's understand how to use the to_a method

Shuffle method

The shuffle method randomly swaps the elements of the array to get it. Source: First Ruby! Randomly acquire / replace arrays | sample / shuffle

-Join method

The join method is used when you want to combine the elements of an array into a single string. The join method converts each element of the array to a string and joins the arguments as delimiters. Source: Active engineers explain how to use Ruby's join method [for beginners]

Conclusion: write like this

('a'..'z').to_a.shuffle[0..7].join

Try running the command in the terminal. Enter ʻirb` and then enter the command.

Terminal


munetomokazushi@mba ~ % irb
irb(main):001:0> ('a'..'z').to_a.shuffle[0..7].join
=> "yahxwgti"

An 8-character random alphabet was output.

I will take a closer look

Disassemble.

irb(main):001:0> ('a'..'z')

First, describe that it is in the range from the alphabet string 'a' to'z'. .. is a Range object. .. includes the last character, but...does not include the last character. Caution.

irb(main):001:0> ('a'..'z').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

It became an array with the .to_a method.

irb(main):001:0> ('a'..'z').to_a.shuffle
=> ["o", "c", "q", "i", "m", "a", "k", "l", "t", "x", "z", "w", "n", "v", "b", "s", "h", "u", "r", "e", "g", "y", "f", "j", "p", "d"]

The array was shuffled with the shuffle method. (Shuffled every time you run)

irb(main):001:0> ('a'..'z').to_a.shuffle[0..7]
=> ["r", "f", "b", "x", "y", "m", "g", "t"]

The shuffled array is acquired for 8 characters from the beginning. Note that the array starts at 0.

irb(main):001:0> ('a'..'z').to_a.shuffle[0..7].join
=> "yahxwgti"

Finally, the join method was used to join the elements of the array into a single string.

2020.8.24 postscript

I received a comment, so please quote and add it. Thank you, @ nodai2h_ITC!

This method does not generate a string that has the same character more than once, such as "agrjesao". For example, if you write a program for the third game of rock-paper-scissors, and if you write a program that doesn't make a move once, you wouldn't call it a "random move". Besides, this method cannot create a random alphabet string of 30 characters, for example, which exceeds the number of alphabet characters. So, how about a way to generate a "random alphabet string" that allows the same characters?

chars = ('a'..'z').to_a # = *'a'..'z'But yes
8.times.map{ chars.sample }.join

This result looks like this.

irb(main):009:0> chars = ('a'..'z').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
irb(main):010:0> 8.times.map{ chars.sample }.join
=> "bjtaniyw"
irb(main):011:0> 8.times.map{ chars.sample }.join
=> "ntbtrdml"
irb(main):012:0> 8.times.map{ chars.sample }.join
=> "ajsgpcwn"
irb(main):013:0> 8.times.map{ chars.sample }.join
=> "vxdgakuc"
irb(main):014:0> 8.times.map{ chars.sample }.join
=> "xknqtmcq" #The same alphabet appears twice. It is displayed properly at random

Let's define a method to generate a random string

# string_Define shuffle method
def string_shuffle(s)
  s.split('').shuffle.join
end

#Try to call
string_shuffle("foobar")
# string_The result of calling the shuffle method
=> "fboora" 

By the way

irb(main):005:0> ('Ah'..'Hmm').to_a.shuffle[0..7].join
=> "Gofukuporekariso"

You can also use hiragana.

Summary

-It can also be used when creating random subdomains. -If you want to run it on the console, enter rails c in the terminal to start the console.

reference

[Ruby] Let's understand how to use the to_a method First Ruby! Randomly acquire / replace arrays | sample / shuffle Active engineers explain how to use Ruby's join method [for beginners]

Recommended Posts

[Ruby] How to generate a random alphabet string
How to change a string in an array to a number in Ruby
[Android] How to convert a character string to resourceId
How to generate a primary key using @GeneratedValue
How to automatically generate a constructor in Eclipse
How to manually generate a JWT with Rails Knock
[Java] How to cut out a character string character by character
Ruby Regular Expression Extracts from a specific string to a string
[Ruby/Rails] How to generate a password in a regular expression
How to use Ruby return
Convert to Ruby Leet string
How to leave a comment
[Ruby] How to comment out
How to use String [] args
Ruby: How to use cookies
[Ruby] How to write blocks
How to insert a video
How to create a method
Cut out a Ruby string
[Ruby] How to split each GraphQL query into a file
How to divide a two-dimensional array into four with ruby
[Java] How to convert a character string from String type to byte type
Learning Ruby with AtCoder 13 How to make a two-dimensional array
[Java] How to use substring to cut out a character string
How to display a graph in Ruby on Rails (LazyHighChart)
How to add columns to a table
How to iterate infinitely in Ruby
How to make a Java container
How to install ruby through rbenv
How to use Ruby on Rails
How to sign a Minecraft MOD
[Ruby] How to use any? Method
[Java] How to create a folder
How to write a ternary operator
[Swift] How to send a notification
How to make a splash screen
How to make a Maven project
How to use Ruby inject method
How to make a Java array
How to execute Ruby irb (interactive ruby)
How to check for the contents of a java fixed-length string
[Xcode] How to add a README.md file
How to execute a contract using web3j
How to sort a List using Comparator
How to get date data in Ruby
[Ruby on Rails] How to use CarrierWave
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Personal memo] How to interact with a random number generator in Java
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Basic] How to write a Dockerfile Self-learning ②
How to insert a video in Rails
How to add a new hash / array
How to create a Maven repository for 2020
Ruby length, size, count How to use
How to make a Discord bot (Java)
How to output Java string to console screen
How to override in a model unit test so that Faker can be used to generate random values
How to get the current date as a string in yyyyMMdd format
[Java] How to use substring to cut out a part of a character string
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
Extract a part of a string with Ruby