我在哪里错过了这个Ruby脚本中的“结束”?

时间:2015-10-20 19:54:30

标签: ruby

我正在敲击我不断收到的错误消息,读取“语法错误,意外的keyword_end,期待输入结束”。我找不到我生命中的错误。它可能看起来很邋,,我是新手。此外,任何有关防止这一特定问题的提示也将不胜感激!

$move_direction_hash = {"N" => [0,1], "E" => [1,0], "S" => [0,-1], "W" => [-1,0]}
$cardinal_directions = ["N", "E", "S", "W"]

class Martian

attr_accessor :coordinate_x, :coordinate_y, :bearing, :direction_string

def initialize (coordinate_x, coordinate_y, bearing, direction_string)
    @coordinate_x = coordinate_x
    @coordinate_y = coordinate_y
    @bearing = bearing
    @direction_string = direction_string
end


def check_valid
    @coordinate_x.between?(0, $boundaries[0]) && coordinate_y.between?(0, $boundaries[1])
        return true
    end
end


#will be second and last called in source code
def get_final
    return "#{coordinate_x} #{coordinate_y} #{bearing}"
end     

def move_forward
    # find where in the hash the bearing is
    position_array = $move_direction_hash[@bearing]
    # returns a temporary variable
    # that is the 
    test_x = @coordinate_x + position_array[0]
    test_y = @coordinate_y + position_array[1]
    if $rovers_on_grid.include?([test_x.to_s, test_y.to_s])
        puts "Stopping Martian. You're about to crash!"
        get_final
        break
    else
        @coordinate_x = test_x
        @coordinate_y = test_y
        if check_valid == false
            puts "Stopping Martian. About to run off the plateau."
            get_final
            break
        else
            return @coordinate_x, @coordinate_y
        end
    end
end

def add_to_grid
$rovers_on_grid << [@x_coordinate, @y_coordinate]
end

def read_instructions       
    @direction_string.each_char do |direction|
        if direction == "L" || direction  == "R"
            position = $cardinal_directions.index(@bearing)
            if direction == "L"
                position = (position - 1)%4
                $cardinal_directions[position]
            elsif direction == "R" 
                position = (position + 1)%4
                $cardinal_directions[position]
            else
                puts "Error!"
            end
        @bearing = $cardinal_directions[position]
        elsif direction == "M"      
            move_forward
        end
    end
end
end

1 个答案:

答案 0 :(得分:3)

此错误位于check_valid方法中。你错过了if。

def check_valid
    if @coordinate_x.between?(0, $boundaries[0]) && coordinate_y.between?(0, $boundaries[1])
        return true
    end
end

就像steenslag提到的那样,if语句不是必需的。你可以写:

def check_valid
    return @coordinate_x.between?(0, $boundaries[0]) && coordinate_y.between?(0, $boundaries[1])
end