after playing morning(i still new this), have decided ask experts.
this quest:
you going given word. job return middle character of word. if word's length odd, return middle character. if word's length even, return middle 2 characters.
this have far:
def median(string) array = string.split(//) case array when array.length == 1 return array[0] when array.length == 2 return array[0] + array[1] when array.length.odd? && array.length >= 3 return array[(array.length - 1) / 2] when array.length.even? && array.length >= 4 return array[((array.length / 2 ) - 1)] + array[(array.length / 2)] else nil end end puts median("testing")
what wrong code. runs delivers nothing. hugely appreciated.
you need remove array
line case array
. did change code , works fine:
def median(string) array = string.split(//) case when array.length == 1 return array[0] when array.length == 2 return array[0] + array[1] when array.length.odd? && array.length >= 3 return array[(array.length - 1) / 2] when array.length.even? && array.length >= 4 return array[((array.length / 2 ) - 1)] + array[(array.length / 2)] else nil end end
in initial version of code, having case array
meant on each branch ruby compare "when" value (which boolean value) array, never boolean, therefore never equal of branches. why else nil
branch exit point of case
block.
changing case array
case
tell ruby not need performa comparison, evaluate each branch condition , execute first 1 true.
this being said, code can simplified in few ways:
- there's no need convert string array; string indexing work fine in case
- the conditions
&& array.length >= 3
,&& array.length >= 4
superfluous; lower value hitarray.length == 1
orarray.length == 2
branches - the
array.length == 1
orarray.length == 2
branches not special; can treat them in odd/even length cases.
applying these considerations ended code, works ok:
def word_median(word) half = word.length / 2 case when word == '' '' when word.length.odd? word[half] else word[half - 1..half] end end
Comments
Post a Comment