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?
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.
'abcdef'.gsub(/./){|s| s.send(%i[upcase downcase].sample)}
# => "aBCdEf"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With