I want to know the simplest way to randomly generate a string in Ruby

Asked 2 years ago, Updated 2 years ago, 125 views

I'm embarrassed because it's such a simple question.

Except for lowercase letters, I want to randomly extract 8 capital letters.

For me,

value = ""; 8.times{value  << (65 + rand(25)).chr}
#Including lowercase letters,
value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

But it looks so dirty. I'm curious if there's another chord ㅜ<

random ruby

2022-09-22 22:10

1 Answers

There are many ways, but I can think of one

#Simpleest Method - Lowercase
('a'..'z').to_a.shuffle[0,8].join

#Extend to uppercase
m = [*('a'..'z'),*('A'..'Z')].shuffle[0,8].join

#Lowercase letters
(0...8).map { (65 + rand(26)).chr }.join

#Lowercase letters
(0...50).map { ('a'..'z').to_a[rand(26)] }.join

That's about it.


2022-09-22 22:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.