I have the following problem:
Given an
Array, apply a certain methodxto eachArrayelement (yielding a newArray), with the restriction that array elements which arenil, 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
Enumerablethus it can be applied to sets, queues and so on. \$\endgroup\$size? \$\endgroup\$