class RuboCop::Cop::Style::MapToHash


{foo: bar}.to_h { |k, v| [k.to_s, v.do_something] }
# good
{foo: bar}.collect { |k, v| [k.to_s, v.do_something] }.to_h
# bad
something.to_h { |v| [v, v * 2] }
# good
something.map { |v| [v, v * 2] }.to_h
# bad
@example
is not an ‘Enumerable`.
This cop is unsafe, as it can produce false positives if the receiver
@safety
transformed.
also change this pattern if only hash keys or hash values are being
NOTE: `Style/HashTransformKeys` and `Style/HashTransformValues` will
written with just `to_h` in Ruby >= 2.6.
This cop looks for uses of `map.to_h` or `collect.to_h` that could be

def autocorrect(corrector, to_h, map)

def autocorrect(corrector, to_h, map)
  removal_range = range_between(to_h.loc.dot.begin_pos, to_h.loc.selector.end_pos)
  corrector.remove(removal_range)
  corrector.replace(map.loc.selector, 'to_h')
end

def on_send(node)

def on_send(node)
  return unless (to_h_node, map_node = map_to_h?(node))
  message = format(MSG, method: map_node.loc.selector.source)
  add_offense(map_node.loc.selector, message: message) do |corrector|
    # If the `to_h` call already has a block, do not auto-correct.
    next if to_h_node.block_node
    autocorrect(corrector, to_h_node, map_node)
  end
end