首页 > 解决方案 > 根据用户输入循环创建

问题描述

我正在创建一种算法来按半径长度对杯子进行排序。输入将是

2  
red 10       
green 7

并且输出是

green
red

我的方法是看到第一个输入是 2 我必须创建 2 个具有颜色和半径属性的杯子。如此处所示:

class Cup
    attr_accessor :colour, :radius

    def initialize(colour, radius)
        @colour = ""
        @radius = 0
    end

    def number_of_cups
        puts "How many cups are there?".chomp
        gets.times do 
            Cup.new("", 0)
        end
    end
end

undefined method当我尝试访问 Cup.number_of_cups时收到错误消息。我的问题是,例如,如果我输入,3那么我会有3新的杯子对象吗?

标签: rubyalgorithmfunctionirb

解决方案


你需要用红宝石清除基础

class Cup
    attr_accessor :colour, :radius

    def initialize(colour='No Colour', radius=0)
        @colour = colour
        @radius = radius
    end
end

puts "How many cups are there?"
cups = []
gets.to_i.times do |n| 
  puts "Enter Cup-#{n+1} colour & radius:"
  c = gets.chomp
  r = gets.to_i
  cups << Cup.new(c, r)
end

sorted_cups = cups.sort_by { |x| x.radius }

此外,您可以显示 sorted_cups


推荐阅读