Nas Ah
Nas Ah

Reputation: 61

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

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)}"

Upvotes: 3

Views: 294

Answers (2)

iGian
iGian

Reputation: 11193

Just to have another option:

def random_case(*names)
  name = names.sample.downcase
  [true, false].sample ? name.upcase : name
end

So

10.times do
  p random_case('Kirk', 'Spock')
end

Upvotes: 0

Ursus
Ursus

Reputation: 30071

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

Upvotes: 7

Related Questions