Reputation: 105
The two identical functions being called here output a string of numbers that vary in length each time. My question is how could I compare the length of them both and then do something with it?
For example: if random_method(2) length < random_method(3) length --> do this
def random_method()
rand1 = rand(2)
if rand1 == 1
rand2 = rand(1..25)
else
rand2 = 0
end
rand2
end
def random_method2()
x_vals = [99]
x_vals << x_vals.last - random_method while x_vals.last > 0
puts ": #{x_vals.join(", ")}"
end
def random_method3()
x_vals = [99]
x_vals << x_vals.last - random_method while x_vals.last > 0
puts ": #{x_vals.join(", ")}"
end
random_method2()
random_method3()
Upvotes: 0
Views: 44
Reputation: 107022
At the moment you only store the arrays in local variables within the methods but do not return the generated array (you only print a string representation of the arrays). To compare and to do something with the arrays you need to return the arrays and store them in variables.
Something like this might works:
def random_number
if rand(2) == 1
rand(1..25)
else
0
end
end
def random_array
array = [99]
array << (array.last - random_number) while array.last > 0
puts array.inspect
array
end
array_1 = random_array
array_2 = random_array
if array_1.length < array_2.length
puts "Array 1 is shorter"
else
puts "Array 1 is longer or equal in size to Array 2"
end
Note that I refactored your methods a bit to remove the duplication and to follow common Ruby idioms.
Upvotes: 1