我几天前就开始学习Ruby了,而且我很难确定为什么我会得到'没有方法'对于明确定义的几种方法的错误。我怀疑有一些关于Ruby如何在后端工作的重要信息,我错过了。这是类代码;它只是制作自定义类的基本练习:
class OrangeTree
def initialize
@height = 1.0
@age = 0
@number_of_oranges = 0
end
def yearPasses
@age = @age + 1
@height = @height + 1.5
if @age >= 50
puts 'The orange tree has died'
exit
else
if @age > 3
@number_of_oranges = 10 + @age
end
puts 'A year passes.'
puts 'Your tree is ' + @age.to_s + ' years old.'
puts
end
def height
puts 'The tree is now ' + @height.to_s + ' feet tall.'
puts
end
def countOranges
puts 'There are ' + @number_of_oranges.to_s + ' oranges in the tree.'
puts
end
def pickOrange
if @number_of_oranges > 0
@number_of_oranges -= 1
puts 'You ate an orange. YUM!'
else
puts 'There are no oranges left to pick.'
end
end
end
这是执行代码:
tree = OrangeTree.new
puts 'You just bought an orange tree!'
x = 0
while x == 0
puts 'What would you like to do? Measure, Count Oranges, Pick Orange, Pass Year'
action = gets.chomp
if action.downcase == 'measure'
tree.height
puts
else
if action.downcase == 'count oranges'
tree.countOranges
puts
else
if action.downcase == 'pick orange'
tree.pickOrange
puts
else
if action.downcase == 'pass year'
tree.yearPasses
puts
else
puts 'Invalid selection.'
puts
end
end
end
end
end
end
方法pickOrange初始化,yearPasses全部工作(虽然由于某种原因,在yearPasses执行超过4次之后树上仍然有0个橙子)。真正的问题是height和countOranges方法,每个方法都返回“无法”方法'错误。对于初学Ruby编码器来说,这个错误似乎相当普遍,但我找到的其他答案帖子似乎都没有适用于我的实例。在此先感谢您的帮助!
答案 0 :(得分:1)
您在这里缺少end
:
def yearPasses
@age = @age + 1
@height = @height + 1.5
if @age >= 50
puts 'The orange tree has died'
exit
else
if @age > 3
@number_of_oranges = 10 + @age
end
# << ------ MISSING END
puts 'A year passes.'
puts 'Your tree is ' + @age.to_s + ' years old.'
puts
end
改为将else
改为elsif
。
def yearPasses
@age = @age + 1
@height = @height + 1.5
if @age >= 50
puts 'The orange tree has died'
exit
elsif @age > 3
@number_of_oranges = 10 + @age
end
puts 'A year passes.'
puts 'Your tree is ' + @age.to_s + ' years old.'
puts
end