Basic Ruby - Need simple explanation of what an if/else statement is doing -
for basic auto class exercise, asked create drive method should take input number of miles driven, alter position accordingly , cut down fuel @ rate of 20 miles per gallon.
i understand basic concept of need , how if/else statement works, need help breaking downwards if/else statement more 'layman terms' happening content.
def initialize @fuel = 10 @distance = 0 end def drive(miles) if (@fuel - miles/20.0) >= 0 @distance += miles @fuel -= miles/20.0 else @distance += @fuel * 20.0 @fuel = 0 puts "you're out of gas!" end
you set fuel value of 10 , distance 0.
when drive x
amount of miles (hence why miles input), have see if you're out of gas.
if amount of fuel minus number of miles traveled, divided 20, greater or equal 0, set distance traveled distance + amount of miles traveled (+=
shorthand @distance = @distance + miles
). think if
may need clarification though: "fuel - miles, divided twenty"? or "fuel - miles/20", order of operations comes play?
anywho, shorthand +=
:
@distance = @distance + miles
then set fuel amount of fuel minus amount of miles traveled, divided 20 (-=
shorthand, similar before.)
@fuel = @fuel - miles/20.0
however, otherwise (the else), set distance
@distance = @distance + fuel *20
then set fuel 0, , print out string "you're out of gas!".
ruby
No comments:
Post a Comment