ruby - What are the differences between "each", "foreach", "collect" and "map"? -
this question has answer here:
it seems there lot of ways loop on enumerable in ruby. there differences between each, foreach, or in collect, map or other similar methods?
or there reason shouldn't use methods in situations?
collect/map equivalent. differ each in each executes block each element, whereas collect/map return array results of calling block each element. way put might be, each expected do each element, whereas map expected transform each element (map onto else).
you use collect or map anywhere each used, , code still work. less efficient because collects results in array, unless ruby implementation realizes doesn't have bother creating array because it's never used.
another reason use each instead of map or collect out reading code. if see each can okay, we're use each element of data something. if see map i'm expecting see new data being created, based on remapping of old data.
with regards map vs. collect it's matter of preference, should pick 1 , stick consistency.
Comments
Post a Comment