I'm new to ruby and I'm having a hard time trying to figure out how to calculate a random travel time until it passes 1000 miles. So far, I can't figure out why it doesn't output the results, it just stays with the user input. Help please
def travel_time()
printf "Pick a vehicle: \n"
printf "1. Bicycle \n"
printf "2. Car \n"
printf "3. Jet Plane \n"
puts "Choose 1-3: \n"
vehicle = gets.chomp
case vehicle
when "1"
#Bicycle: 5-15 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(5...15)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
when "2"
#Car: 20-70 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(20...70)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
when "3"
#Jet Plane: 400-600 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(400...600)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
end
end
travel_time
You have an infinite loop here:
until distance > 1000 do
speed = Random.rand(5...15)
distance = speed * 1
time = time + 1
end
This loop will never ende because the biggest value distance
can get is 15
, so i think you want to add to distance
, not replace it; son try using +=
instead of =
:
until distance > 1000 do
speed = Random.rand(5...15)
distance += speed * 1
time = time + 1
end
Same goes for all loops in each case.
How can I save the maximum speed and return it in a statement like I have done?
One way to do it would be to add another variable (i.e. max_speed
) and assign speed
value to it whenever speed
is greater than max_speed
:
time = 0
distance = 0
max_speed = 0
until distance > 1000 do
speed = Random.rand(5...15)
max_speed = speed if speed > max_speed
distance += speed * 1
time = time + 1
end
puts "The maximum speed was #{max_speed} miles per hour"
Another way would be to use an array (although i prefer the first option):
speed = []
until distance > 1000 do
speed << Random.rand(5...15)
distance += speed.last * 1
time = time + 1
end
puts "The maximum speed was #{speed.max} miles per hour"