iteration - Is there an implicit keyword in this Ruby Array map code? -
is there keyword can use explicitly tell map function result of particular iteration should be?
consider:
a = [1,2,3,4,5] a.map |element| element.to_s end
in above example element.to_s implicitly result of each iteration.
there situations don't want rely on using last executed line result, prefer explicitly result in code.
for example,
a = [1,2,3,4,5] a.map |element| if some_condition element.to_s else element.to_f end end
might easier me read if written like:
a = [1,2,3,4,5] a.map |element| if some_condition result_is element.to_s else result_is element.to_f end end
so there keyword can use in place of result_is
?
return
return calling function, , break
stop iteration early, neither of i'm looking for.
yes, there is, it's called next
. however, using next
in particular case not improve readability. on contrary, a) confuse reader , b) give him impression author of code doesn't understand ruby.
the fact everything expression in ruby (there no statements) , every expression evaluates value of last sub-expression in expression fundamental ruby knowledge.
just return
, next
should used when want "return" middle of block. usually, use guard clause.
Comments
Post a Comment