class RuboCop::Cop::Style::UnpackFirst
‘foo’.unpack1(‘h*’)
# good
’foo’.unpack(‘h*’).at(0)
‘foo’.unpack(‘h*’).slice(0)
‘foo’.unpack(‘h*’)[0]
‘foo’.unpack(‘h*’).first
# bad
@example
which can be replaced with the shorter method ‘unpack1`.
This cop checks for accessing the first element of `String#unpack`
def first_element_range(node, unpack_call)
def first_element_range(node, unpack_call) Parser::Source::Range.new(node.loc.expression.source_buffer, unpack_call.loc.expression.end_pos, node.loc.expression.end_pos) end
def on_send(node)
def on_send(node) unpack_and_first_element?(node) do |unpack_call, unpack_arg| range = first_element_range(node, unpack_call) message = format(MSG, receiver: unpack_call.receiver.source, format: unpack_arg.source, method: range.source) add_offense(node, message: message) do |corrector| corrector.remove(first_element_range(node, unpack_call)) corrector.replace(unpack_call.loc.selector, 'unpack1') end end end