HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Custom map on `Array`

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycustommap

Problem

I have the following problem:

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: :size

Default element: -1

Expected 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, not Array, so that the method can be applied to other objects such as instances of Hash, Set, etc.



  • Use respond_to? rather than a type-check against nil, 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
end

Context

StackExchange Code Review Q#132110, answer score: 3

Revisions (0)

No revisions yet.