I am using Ruby 1.9 and I would like to know if there is a “better” way to write the following code.
array_one = []
array_two = []
some_array.each { |value|
array_one << value.id
array_two << value.name
}
I “don’t like” to initialize array_one and array_two like in the above example and then add in those value.id and value.name. This because and mostly for a better understanding and reading of the code in my application.
I would like to provide the same functionality but with a “better” coding. Is it possible?
The code pattern you have there, is usually a sure sign of a
fold(or more generally a catamorphism) wanting to get out. Ruby does provide a built-in method for folding, for historical reasons it is calledinject.Untested:
Not sure whether you think this is “better” or not. For someone who understands what a
foldis, this is probably clearer. For someone who doesn’t, it’s probably not.(Although I think that if you don’t understand what a
foldis, then you are not a very good Ruby programmer, or even a very good programmer at all, but that is just my opinion.)However, saying that some iteration is a
foldisn’t really terribly useful, sincefoldis a general method of iteration (which means that every form of iteration can be expressed as afold). What you really have here, is amap:Note that this will traverse
some_arraytwice. However, unless you have credible benchmarks and profiling results that show that this double traversal is a major source of performance troubles in your application, you really shouldn’t worry about that.