patternrubyMinor
Custom map on `Array`
Viewed 0 times
arraycustommap
Problem
I have the following problem:
Given an
Array:
Method:
Default element:
Expected result:
I implemented this by adding a method
I'm looking for an improvement of my current solution. Can the solution be improved in the following sense?
Given an
Array, apply a certain method x to each Array element (yielding a new Array), with the restriction that array elements which are nil, should be mapped to some default value. Method and default element are parameters. Example:Array:
['abc',nil,'defg']Method:
:sizeDefault element:
-1Expected result:
[3, -1, 4]I implemented this by adding a method
map_with to the Array class:class Array
def map_with(accessor, default_value=nil)
map {|e| e.nil? ? default_value : e.send(accessor) }
end
end
['abc',nil,'defg'].map_with(:size, -1)I'm looking for an improvement of my current solution. Can the solution be improved in the following sense?
- Provide the same result with simpler code
- Make the function more flexible (more generally useful) by not adding too much code
Solution
My implementation is very similar to yours, with only a few small tweaks:
module Enumerable
def map_with(accessor, default_value: nil)
map { |e| e.respond_to?(accessor) ? e.send(accessor) : default_value }
end
end- Use
Enumerable, notArray, so that the method can be applied to other objects such as instances ofHash,Set, etc.
- Use
respond_to?rather than a type-check againstnil, for better duck-typing robustness.
- Use a named parameter, for improved code clarity.
Code Snippets
module Enumerable
def map_with(accessor, default_value: nil)
map { |e| e.respond_to?(accessor) ? e.send(accessor) : default_value }
end
endContext
StackExchange Code Review Q#132110, answer score: 3
Revisions (0)
No revisions yet.