class RuboCop::Cop::Performance::Sample

This cop is used to identify usages of `shuffle.first`, `shuffle.last` and `shuffle[]` and change them to use `sample` instead.

@example

# bad
[1, 2, 3].shuffle.first
[1, 2, 3].shuffle.first(2)
[1, 2, 3].shuffle.last
[1, 2, 3].shuffle[2]
[1, 2, 3].shuffle[0, 2]    # sample(2) will do the same
[1, 2, 3].shuffle[0..2]    # sample(3) will do the same
[1, 2, 3].shuffle(random: Random.new).first

# good
[1, 2, 3].shuffle
[1, 2, 3].sample
[1, 2, 3].sample(3)
[1, 2, 3].shuffle[1, 3]    # sample(3) might return a longer Array
[1, 2, 3].shuffle[1..3]    # sample(3) might return a longer Array
[1, 2, 3].shuffle[foo, bar]
[1, 2, 3].shuffle(random: Random.new)

Constants

MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/performance/sample.rb, line 36
def autocorrect(node)
  ShuffleAnalyzer.new(node).autocorrect
end
on_send(node) click to toggle source
# File lib/rubocop/cop/performance/sample.rb, line 30
def on_send(node)
  analyzer = ShuffleAnalyzer.new(node)
  return unless analyzer.offensive?
  add_offense(node, analyzer.source_range, analyzer.message)
end