Nested conditional statements in Ruby -
my issues two-fold:
i didn't realize nest multiple conditionals this. seems pretty nasty. think know what's going on here, gets explain can concept?
since don't understand nested conditionals well, i'm bit lost on refactor, area pretty weak in begin with. y'all kind present possible refactor solutions explanations? limited understanding greatly.
def valid_triangle?(a, b, c, sum) if != 0 || b != 0 || c != 0 if >= b largest = sum += b else largest = b sum += end if c > largest sum += largest largest = c else sum += c end if sum > largest return "true" else return "false" end else return false end end
you can trim down considerably doing more ruby-like way:
def valid_triangle?(*sides) case (sides.length) when 3 sides.sort! sides[0] + sides[1] >= sides[2] else false end end
whenever possible, try , express logic series of transformations on data, it's lot easier follow. in case treat incoming points array , sort them rather having special-case logic each point. special case code trouble, hard test, , prone subtle failure if make tiny mistake.
it's worth noting in ruby should have if
statements formatted this:
if condition # ... elsif condition # ... else # ... end
including code following else
may valid syntax, it's confusing at. seems you're testing against largest == b
, have made mistake, doing assignment inadvertently, when that's content of else
block, not condition elusive
.
this code can updated include tests negative lengths, adding sides[0] > 0
part of logic.
also, embrace ruby implicit return
last value provided 1 returned method. case
statement propagates values 1 triggered, making convenient passing things through.
Comments
Post a Comment