Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubocop Lint/Void: Literal used in void context

I have been running rubocop and encountered a Lint/Void: Literal used in void context offence.

the following code:

routes_and_postcodes.each do |hash|
  2..7.each do |i|
    route = Route.where(name: hash[:route]).first if postcode.delete(" ").first(i) == hash[:postcode].delete(" ")
  end
end

I have read the docs, but still cant understand what the issue is. In context, the full code is here:

def choose_own_van_route(postcode)
route = nil
routes_and_postcodes = []
Route.all.each do |r|
  route_postcodes = r.postcode_array
  route_postcodes.each do |pc|
    routes_and_postcodes << { postcode: pc, route: r.name }
  end
end
routes_and_postcodes.each do |hash|
  2..7.each do |i|
    route = Route.where(name: hash[:route]).first if postcode.delete(" ").first(i) == hash[:postcode].delete(" ")
  end
end
route || Route.create(cut_off_time_mins_since_midnight: 0, name: "BLANK ROUTE HAD TO BE ASSIGNED")
end 

Thanks

like image 327
daveanderson88 Avatar asked Jun 12 '18 15:06

daveanderson88


1 Answers

2..7.each do |i|
  # ...
end

...is invalid code!! Have you tried running it? You'll see the following error:

NoMethodError: undefined method `each' for 7:Integer

To fix this, you need to define the Range in brackets:

(2..7).each do |i|
  # ...
end

The rubocop error is in relation to this: Since if there were an each method defined on Integer (there isn't, but rubocop doesn't know that), then the code would be valid but the 2..<something> range definition would serve no purpose; it's a literal with a void context.

like image 103
Tom Lord Avatar answered Oct 09 '22 21:10

Tom Lord