Search code examples
c++rubyenumerable

How to use Ruby's Enumerable .map method to do something similar to map in C++


map(-30, -89.75, 89.75, 0, 360) 

I'm looking for something like this where:

  • -30 is the input value.
  • -89.75 to 89.75 is the range of possible input values
  • 0 - 360 is the final range to be mapped to

I was told there is a way to do this using http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map

.. however its not readily apparent !


Solution

  • If I'm understanding correctly, I think you just want to uniformly map one range onto another. So, we just need to calculate how far through the input range it is, and return that fraction of the output range.

    def map_range(input, in_low, in_high, out_low, out_high)
      # map onto [0,1] using input range
      frac = (input - in_low) / (in_high-in_low)
      # map onto output range
      frac * (out_high-out_low) + out_low
    end
    

    Also, I should note that map has a bit of a different meaning in ruby, and a more appropriate description would probably be transform.