Get random data from previous methods

#1

I have this code:

name = “Jordan”

def upper(string)
string.upcase
end

def lower(string)
string.downcase
end

def random_name
[“Ollie”, “Ana”].sample
end

def random_case(string)
[upper(string), lower(string)].sample
end

Please write your code between this line…

… and this line

puts “My name is #{random_both()}”

I need to write the simplest code possible to make random_both return “My name is ollie” or “My name is OLLIE” or “My name is ANA” or “My name is ana”

#2

You have already done it!
Let me show what I meant:

#!/usr/bin/ruby -w

def upper(string)
	string.upcase
end

def lower(string)
	string.downcase
end

def random_name
	%w(Ollie Ana).sample
end

def random_case(string)
	[upper(string), lower(string)].sample
end

puts "My name is #{random_case(random_name)}"

But it’s a long code for a short outcome. Methods are needed if your code needs to call them more than once. For this simple code, it’s no good to have methods for everything.
And of course Object methods upper and lower makes few sense because you have to call lower('string'), instead you can do 'string'.downcase.
If it was in a class, that would be fine though!

Yes, one of my benchmark showed method calls are indeed slower

(https://github.com/Souravgoswami/ruby-masterclass/blob/master/Section%2040:%20introduction%20to%20Benchmarking/Part7_Benchmarking_method_lambda_proc_stabby_lambda_calls.rb)

So the code you wrote is very inefficient and looks ugly…

So in such case, what you can do is:

#!/usr/bin/ruby -w

names = 'Ollie', 'Ana'
puts names.sample.then { |x| 'My name is ' + [x.upcase, x.downcase].sample }

Caveat:
You see both the programs above used the upcase and downcase methods, while sample chose only one value. Both upcase and downcase methods returns a duplicated string. In our case, garbage collector discards the unused value. This is wasteful. To prevent calling both the methods, we can do this:

#!/usr/bin/ruby -w

names, meth = ['Ollie', 'Anna'], [:upcase, :downcase]
puts names.sample.then { |x| 'My name is ' + x.send(meth.sample) }

The output of all the codes can’t be determined, because they are random, but they all will do the job you want. The first one is the least efficient, the second one is so so, the third one is better than the first and the second ones!

Hope this reply helps!