Reputation: 69
I've got this method that is supposed to generate a random selection from an array of constants. But the method won't return the results. In fact It won't return anything I try.
Here is the code:
COLORS = ["B", "G", "R", "O", "Y", "P"]
class Computer
attr_reader :random_code
def initialize
@random_code = secret_code
end
def secret_code
sample_code = []
sample_code << COLORS.sample(4)
return sample_code
end
def add(a, b)
return a + b
end
end
c = Computer.new
c.add(5, 10)
Added the "add" method just to test it out, but it doesn't work aswell. When I say it doesn't work I mean It doesn't show anything in the console.
Upvotes: 1
Views: 373
Reputation: 3010
As @BroiSatse pointed out, the problem is just that you didn't tell Ruby to print anything to the console.
Here is how I would fix and simplify your code:
class Computer
COLORS = ["B", "G", "R", "O", "Y", "P"]
attr_reader :random_code
def initialize
@random_code = secret_code
end
def secret_code
COLORS.sample(4)
end
def add(a, b)
a + b
end
end
c = Computer.new
puts c.add(5, 10)
A couple other things worth noting:
If COLORS
is something inherent to your Computer class, you can pull it into the class and make it a class constant. You can refer to COLORS
as-is from within the class, but just remember that if you want to refer to COLORS
anywhere outside of the class definition, you have to refer to it as Computer::COLORS
in order to access it. The way you have it currently is fine too, this is just a minor code organization thing.
Your secret_code
function can be simplified to just COLORS.sample(4)
. In Ruby, you don't have to use the return
keyword, and it's idiomatic to leave it out whenever it's not needed. The last value in a function definition is what is returned. Also, since Array#sample
already returns an array, there is no need to define an empty Array []
and add to it.
Upvotes: 2