class RuboCop::Cop::Style::UnpackFirst

Checks for accessing the first element of ‘String#unpack` which can be replaced with the shorter method `unpack1`.

@example

# bad
'foo'.unpack('h*').first
'foo'.unpack('h*')[0]
'foo'.unpack('h*').slice(0)
'foo'.unpack('h*').at(0)

# good
'foo'.unpack1('h*')

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/style/unpack_first.rb, line 38
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

Private Instance Methods

first_element_range(node, unpack_call) click to toggle source
# File lib/rubocop/cop/style/unpack_first.rb, line 54
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