【问题标题】:Undefined Method error in Ruby class [closed]Ruby类中的未定义方法错误[关闭]
【发布时间】:2015-07-26 02:37:47
【问题描述】:

我正在尝试为橘子树编写一个简单的类...但出现此错误:pine_orangetree.rb:11:in oneYearPasses': undefined method+' for nil:NilClass (NoMethodError)

当我调用 oneYearPasses 方法时...为什么会这样?

class OrangeTree

    def initalize
        @height = 0
        @oranges = 0
    end



    def oneYearPasses
        @height += 2
        @oranges = 0

        if @height > 7
            @oranges += 10
        end

        if @height < 30
            puts "Another year has passed..."   
        else
            puts "The orange tree died..."
        end     
    end

    def height
        puts "The tree is #{@height} inches tall."
    end

    def countTheOranges
        puts "There are #{@oranges} on the tree."
    end

    def pickAnOrange
        @oranges -= 1
        puts "You picked an orange."
        puts "There are #{@oranges} left."
    end


end

tree1 = OrangeTree.new
tree1.oneYearPasses
tree1.height

【问题讨论】:

    标签: ruby class methods


    【解决方案1】:

    initalize 这个词有错别字。应该是initialize

    并且由于拼写错误,在创建对象时不会调用initalize 方法,因此在创建时未定义实例变量@height。并且您不能在尚不存在的对象上调用 +=

    另外作为旁注,您不应该突然添加太多空白行。这违反了Ruby Style Guide

    【讨论】:

    • 哇。大声笑对不起!这有时让编程变得疯狂令人沮丧。 xD 谢谢!
    • @sickcodeworm 不客气 :) 可能您需要将此标记为已接受的解决方案。
    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多