0

Is there a way to modify the implementation of map() in the Array class such that it only affects certain indices of the array?

Example:

a = [1, 2, 3, 4, 5]
a.map(2..4) { |x| x*2 }

Now, a = [1, 2, 6, 8, 10] since the map function was only used on indices 2 and 3.

3
  • What happened to index 4? Commented Oct 16, 2020 at 0:15
  • Let r = 2..4. Then you need to write a.map.with_index { |n,i| r.cover?(i) ? 2*n : n } #=> [1, 4, 6, 8, 10]. That returns a new array and leaves a unchanged. If you wish to modify a use map! rather than map. See Range#cover?. Commented Oct 16, 2020 at 1:45
  • Sorry about that. I'm still very new to Ruby and forgot that ".." is inclusive. I have fixed it in my question. Commented Oct 17, 2020 at 1:41

1 Answer 1

2

You could (but really shouldn't) do this:

Array.class_eval do
  def map(range = nil)
    return super() if range.nil?
    return self[range].map unless block_given?

    self[range].map { |x| yield x }
  end
end

[1, 2, 3, 4, 5].map(2..4) { |x| x * 2 }
# => [6, 8, 10]

Ruby already has a MUCH more normal/nice/better way of "select only certain indices", with arr[2..4]:

arr = [1, 2, 3, 4, 5]
arr[2..4].map { |x| x * 2 }
# => [6, 8, 10]

I've avoided mutation above, but if you must have that as well, you can do something similar to the above, just with map! instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I would have just used the Ruby implementation of what I was talking about, but my professor ONLY wants us to modify the Array class. I have been trying to solve this problem for a week but it seems my Ruby fundamentals are still not that great. Thank you for providing your insight, I really appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.