Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return random upcase and downcase strings from a lowercase strings array

Tags:

ruby

Is there an efficient way to return a string either in uppercase or in lowercase randomly? I don't want to use upcase or downcase inside an array as follows. Also Array will contain two names, lets say ["Cary", "Ursus"] and the ouput i want would be randomly one of these 4 outcomes. 1- My name is CARY or My name is cary or My name is URSUS or My name is ursus.

def random_case(name)
  name = ["jordan".upcase, "jordan".downcase]
  name.sample
end

puts "My name is #{random_case(name)}"
like image 842
Nas Ah Avatar asked Nov 19 '25 08:11

Nas Ah


1 Answers

What about this one? 0 for upcase, 1 for downcase

def random_case(name)
  rand(2).zero? ? name.upcase : name.downcase
end

rand(2) returns 0 or 1.

If you want to take methods randomly from an array

def random_case(name)
  name.public_send([:upcase, :downcase].sample)
end

Multiple names as requested in comments

def random_case(*names)
  names.map { |name| rand(2).zero? ? name.upcase : name.downcase }
end

You can call this last one with

random_case("Ursus", "Cary")

Last request in comments

def random_case(*names)
  names.sample.public_send([:upcase, :downcase].sample)
end
like image 72
Ursus Avatar answered Nov 21 '25 00:11

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!