class RuboCop::Cop::Style::MapToHash
Looks for uses of ‘map.to_h` or `collect.to_h` that could be written with just `to_h` in Ruby >= 2.6.
NOTE: ‘Style/HashTransformKeys` and `Style/HashTransformValues` will also change this pattern if only hash keys or hash values are being transformed.
@safety
This cop is unsafe, as it can produce false positives if the receiver is not an `Enumerable`.
@example
# bad something.map { |v| [v, v * 2] }.to_h # good something.to_h { |v| [v, v * 2] } # bad {foo: bar}.collect { |k, v| [k.to_s, v.do_something] }.to_h # good {foo: bar}.to_h { |k, v| [k.to_s, v.do_something] }
Constants
- MSG
- RESTRICT_ON_SEND
Public Class Methods
Source
# File lib/rubocop/cop/style/map_to_hash.rb, line 53 def self.autocorrect_incompatible_with [Layout::SingleLineBlockChain] end
Public Instance Methods
Source
# File lib/rubocop/cop/style/map_to_hash.rb, line 57 def on_send(node) return unless (to_h_node, map_node = map_to_h(node)) message = format(MSG, method: map_node.loc.selector.source, dot: to_h_node.loc.dot.source) add_offense(map_node.loc.selector, message: message) do |corrector| # If the `to_h` call already has a block, do not autocorrect. next if to_h_node.block_literal? autocorrect(corrector, to_h_node, map_node) end end
Also aliased as: on_csend
Private Instance Methods
Source
# File lib/rubocop/cop/style/map_to_hash.rb, line 73 def autocorrect(corrector, to_h, map) removal_range = range_between(to_h.loc.dot.begin_pos, to_h.loc.selector.end_pos) corrector.remove(range_with_surrounding_space(removal_range, side: :left)) if (map_dot = map.loc.dot) corrector.replace(map_dot, to_h.loc.dot.source) end corrector.replace(map.loc.selector, 'to_h') return unless map.parent.block_type? if (argument = destructuring_argument(map.parent.arguments)) corrector.replace(argument, argument.source[1..-2]) end end
rubocop:disable Metrics/AbcSize