Ad

Code Doesn't Run When I Had One More Elsif Statement

Can anyone please explain to me why my code doesn't run when I have my second elsif statement in. I'm sure it's something simple but I've been over it a few times, wrote out the code again and still can't work out the bug. It only bugs when line 25 to 30 are in and says

undefined method`[]' on line 35

but this error will change to something else if I run it again.

So this is affecting line_three as a test I am trying "Southern Cross" for the starting location and "Windsor" for the destination.

This is an error message I receive:

Traceback (most recent call last):
pt_planner.rb:35:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

another is:

Traceback (most recent call last):
pt_planner.rb:33:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)

Hope this edit helps

require 'pry'

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
line_two = ['Flagstaff', 'Melbourne Central', 'Parliament', 'Richmond', 'Kooyong', 'Tooronga']
line_three = ['Southern Cross', 'Richmond', 'South Yarra' ,'Prahran' 'Windsor']

#1 where would you like to go capture input
puts "what is your starting location?"
user_input_1 = gets.chomp
puts "what is your end location"
user_input_2 = gets.chomp


if line_one.include?(user_input_1) == true and 
    line_one.include?(user_input_2) == true
    origin_index = line_one.index(user_input_1)
    destination_index = line_one.index(user_input_2) 
    route = line_one
elsif  
    line_two.include?(user_input_1) == true and 
    line_two.include?(user_input_2) == true
    origin_index = line_two.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_two
elsif
    line_three.include?(user_input_1) == true and
    line_three.include?(user_input_2) == true
    origin_index = line_three.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_three
end

stops = destination_index - origin_index

puts "origin: #{route[origin_index]}\ndestination: #{route[destination_index]}\n#{route.slice(origin_index +1, stops)}\n stops total: #{destination_index - origin_index}"

binding.pry
Ad

Answer

You tried to search in wrong array

Change

destination_index = line_two.index(user_input_2)

to

destination_index = line_three.index(user_input_2)

Also you don't need to compare with true. include? returns true or false, that's enough. It's better to use && instead of and. And put condition on one line with elsif

You can refactor like this to check both values are in the array

([user_input_1, user_input_2] - line_three).empty?
Ad
source: stackoverflow.com
Ad