虚拟树程序出错 ruby

Error with virtual tree program ruby

我刚开始学习ruby并按照教程制作了这个程序。

我在尝试 运行 时总是遇到错误,而且找不到答案。 该程序假设能够采摘水果,计算水果,给出高度并生长。

C:\Sites\testfolder>ruby orangetree.rb
orangetree.rb:2:in `initialize': wrong number of arguments (1 for 0) (ArgumentEr
ror)
    from orangetree.rb:51:in `new'
    from orangetree.rb:51:in `<class:OrangeTree>'
    from orangetree.rb:1:in `<main>'

C:\Sites\testfolder>

这是程序

class OrangeTree
  def initialize

  @age = 0
  @tall = 0
  @fruit = 0

  puts 'You have planted a new tree!'

  def height
    puts 'The tree is ' + @tall.to_s + 'foot tall.'
  end

  def pickAFruit
if @fruit <= 1
  puts 'There is not enough fruit to pick this year.'
else
  puts 'You pick an orange from the tree.'
  @fruit = @fruit - 1
end
end

  def countOranges
    puts 'The tree has ' + @fruit.to_s + 'pieces of fruit'
  end

  def oneYearPasses
@age = @age + 1
@tall = @tall + 3
@fruit = 0

  if dead?
    puts 'The Orange Tree Dies'
    exit
  end

  if @age > 2
  @fruit = @age*10
  else
  @fruit = 0
  end
end

private

def dead?
  @age > 5
end

end

tree = OrangeTree.new 'tree'
command = ''

while command != 'exit'
  puts 'please enter a command for the virual tree'
  command = gets.chomp
  if command == 'tree height'
    tree.height
  elsif command == 'pick fruit'
    tree.pickAFruit
  elsif command == 'wait'
    tree.oneYearPasses
  elsif command == 'count fruit'
    tree.countOranges
  elsif command == 'exit'
    exit
  else
    puts 'Cant understand your command, try again'
  end
end
end

有人可以帮忙吗?

您有一些语法错误。我已经在下面修复了它们。语法错误是:

  • 你在最后一行有一个额外的 end(用于关闭 class 声明)
  • 您向 OrangeTree.new ("tree") 传递了一个意外的参数。这就是您问题中的 wrong number of arguments (1 for 0) 错误消息所指的内容。
  • 您缺少 end 来关闭您的 initialize 方法声明(在 puts 'You have planted a new tree!' 行之后)

我还修复了缩进,这使代码更具可读性并且更容易发现像这样的语法错误。


class OrangeTree
  def initialize
    @age = 0
    @tall = 0
    @fruit = 0

    puts 'You have planted a new tree!'
  end

  def height
    puts 'The tree is ' + @tall.to_s + 'foot tall.'
  end

  def pickAFruit
    if @fruit <= 1
      puts 'There is not enough fruit to pick this year.'
    else
      puts 'You pick an orange from the tree.'
      @fruit = @fruit - 1
    end
  end

  def countOranges
    puts 'The tree has ' + @fruit.to_s + 'pieces of fruit'
  end

  def oneYearPasses
    @age = @age + 1
    @tall = @tall + 3
    @fruit = 0

    if dead?
      puts 'The Orange Tree Dies'
      exit
    end

    if @age > 2
      @fruit = @age*10
    else
      @fruit = 0
    end
  end

  private

  def dead?
    @age > 5
  end

end

tree = OrangeTree.new
command = ''

while command != 'exit'
  puts 'please enter a command for the virual tree'
  command = gets.chomp
  if command == 'tree height'
    tree.height
  elsif command == 'pick fruit'
    tree.pickAFruit
  elsif command == 'wait'
    tree.oneYearPasses
  elsif command == 'count fruit'
    tree.countOranges
  elsif command == 'exit'
    exit
  else
    puts 'Cant understand your command, try again'
  end
end