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.
2..4. Then you need to writea.map.with_index { |n,i| r.cover?(i) ? 2*n : n } #=> [1, 4, 6, 8, 10]. That returns a new array and leavesaunchanged. If you wish to modifyausemap!rather thanmap. See Range#cover?.