简体   繁体   中英

Why doesn't this Ruby code work?

I am new to programming and I decided to learn ruby. I have just started, so I am still trying to understand many of the concepts and ideas of ruby. Well, I was trying to create my own program with the things I have learnt from the first lessons and so I wrote this small program.

class Car
  def say_brand(aBrand)
    @thebrand=aBrand
  end

  def get_brand
    return @thebrand
  end

  def say_year(aYear)
    @theyear=aYear
  end

  def get_year
    return @theyear
  end

  def say_model(aModel)
    @themodel=aModel
  end

  def get_model
    return @themodel
  end
end

firstcar.say_brand(Toyota)
puts(firstcar.get_brand)
firstcar.say_year(1997)
puts(firstcar.get_year)
firstcar.say_model(Corolla)
puts(firstcar.get_model)

secondcar.say_brand(Subaru)
puts(secondcar.get_brand)
secondcar.say_year(2005)
puts(secondcar.get_year)
secondcar.say_model(Impressa)
puts(secondcar.get_model)

thirdcar.say_brand(Ford)
puts(thirdcar.get_brand)
thirdcar.say_year(2013)
puts(thirdcar.get_year)
thirdcar.say_model(Explorer)
puts(thirdcar.get_model)

When I run it on the command line in my computer this appears:

cars.rb:45:syntax error,unexpected $end,expecting keyword_end

When I run it in the codecademy labs editor for Ruby this appears:

(eval):569: (eval):569: compile error (SyntaxError)
(eval):569: syntax error, unexpected $end, expecting kEND

I was expecting the program to display something similar to this:

-Toyota
-1997
-Corolla
-Subaru
-2005
-Impressa
-Ford
-2013
-Explorer

I would really appreciate if someone could tell me what is wrong with my code, so that I can continue to learn programming.

The error message means that the end of the program was reached while there was still a block open that should have been closed with an end . Proper indentation of code should make such errors obvious.

Other than that, the code posted does not create the objects firstcar , secondcar , or thirdcar (eg, with firstcar = Car.new ). The brand names and car models (eg, Toyota ) also look like you intended them to be strings - if so, they are missing the quotes (eg, 'Toyota' ). (If you intended them to be classes or objects, the code posted does not shown their definitions.)

The get_* and say_* (did you mean set ?) accessors are also not in good Ruby style, although not inherently wrong. Read up on accessors in Ruby.

Use irb . Type in your command line irb , and an interactive Ruby shell will open. In it, enter your lines one by one. I found that there is nothing wrong with your class definition. If you enter your lines one by one and watch the output, you will see which line has the syntax error in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM