Why is this local variable labeled as undefined? - Ruby
I've got a function that goes through an array of objects, and creates a new array of objects based on certain attributes from the original array. When I run this code I get the error
in 'nonstop': undefined local variable or method `sort_list' for main:Object (NameError)
I made sure the sort_list array was initialized outside of the loop, and I've tried initializing it with a certain size too, but I keep getting this error. I'm pretty new to ruby, so what am I doing incorrectly?
开发者_Go百科def nonstop(flight_list)
index = 0
sort_list[] = nil
flight_list.each do |curr|
if (curr.depapt == ARGV[2] && curr.arrapt == ARGV[3])
sort_list[index] = curr
index += 1
end
end
sort_list.sort! { |a,b| a.deptime <=> b.deptime}
sort_list.each do |curr|
puts "#{curr.flightnum}\t#{curr.deptime}\t#{curr.arrtime}"
end
if (sort_list.empty?)
puts "none"
end
end
I think you need to initialize it like this:
sort_list = []
This doesn't throw an error in irb
for me.
You have already got right answer.
I'll make a little refactoring, which can be useful for novice.
def nonstop(flight_list)
sort_list = flight_list.select { |curr| curr.depapt == ARGV[2] && curr.arrapt == ARGV[3] }
sort_list.sort_by! &:deptime
sort_list.each do |curr|
puts "#{curr.flightnum}\t#{curr.deptime}\t#{curr.arrtime}"
end
puts "none" if sort_list.empty?
end
Here is why sort_list[] = nil
does not work in ruby:
[]
On its own is a shortcut for Array.new
[]
after a variable name is calling []
on the variable. So in that context []
is a method.
sort_list is not set to anything, so it is undefined. So sort_list[]
is calling []
on an undefined value
Setting any variable to nil makes it of nil class.
精彩评论