案例和时间的问题

时间:2014-08-07 05:35:12

标签: ruby switch-statement

Ruby初学者在这里,我使用Chris Pine的学习计划开始,我解决了这个橘子树的问题,但我决定稍微修补一下。在以前的版本中,我为one_year_passes方法使用了一堆if / else语句,但我想了解如何实现case以及何时,所以我改变了它。问题是,one_year_passes在调用时不再添加橙子,它只输出nil。我有点卡住了。

class OrangeTree

    def initialize
        @age               = 1 
        @height            = 4
        @number_of_oranges = 0

        puts "An orange tree has been planted. It is #{@height} feet tall."
    end

    def height 
        puts "Your tree is is #{@height} feet tall. It has #{@number_of_oranges} oranges."
    end

    def count
        if @number_of_oranges > 0
            puts "There are #{@number_of_oranges} oranges."
        else
            puts "There are no oranges on the tree."    
        end 
    end

    def pick
        if @number_of_oranges > 0
            @number_of_oranges -= 1
            puts 'That was delicious.'
        else
            puts 'Sadly, there are no oranges.'
        end
    end

    def age
        if @age > 1
            puts "The tree is #{@age} years old."
        else
            puts "The tree is one year old."
        end
    end

    def one_year_passes
        @number_of_oranges = 0
        @age += 1
        @height += 2
        case @age
        when @age == 2 || @age == 3 || @age == 4 then @number_of_oranges += 4
        when @age == 5 || @age == 6 || @age == 7 then @number_of_oranges += 8
        when @age == 8 || @age == 9 || @age == 10 then @number_of_oranges += 12
        when@age == 11 then puts 'The orange has given all it has to give and has died'

            exit
        end
    end
end

1 个答案:

答案 0 :(得分:0)

您可以使用范围:

case @age
when 2..4 then @number_of_oranges += 4
when 5..7 then @number_of_oranges += 8
when 8..10 then @number_of_oranges += 12
when 11 then puts 'The orange has given all it has to give and has died'
end  

case语句使用===运算符,语句的计算方式如下2..4 === @age,依此类推。
请参阅Range#===