Alexander Popov
Alexander Popov

Reputation: 24995

How to randomise upper/lower case of a string in Ruby?

I want to transform 'abcdef' into 'aBCdeF' or 'AbCDEF' or any other random combination of lower and upper case characters. I need to use this with any given string. I am aware of String's #upcase, #swapcase, #capitalize etc., but I don't think there is a built-in method for doing what I want. The best I came up with is something like:

'abcdef'.chars.map { |c| c.send [:upcase, :downcase][rand 2] }.join

Any better ideas?

Upvotes: 3

Views: 1193

Answers (2)

user456814
user456814

Reputation:

You could try something like this, where x is your string:

x.chars.map { |c| (rand 2) == 0 ? c.downcase : c.upcase }.join

The map method takes a block that randomly generates 0 or 1 for each char. If 0, the char is returned as is, otherwise it gets upper-cased.

Upvotes: 6

sawa
sawa

Reputation: 168239

'abcdef'.gsub(/./){|s| s.send(%i[upcase downcase].sample)}
# => "aBCdEf"

Upvotes: 5

Related Questions