ruby - 根据用户输入循环创建
问题描述
我正在创建一种算法来按半径长度对杯子进行排序。输入将是
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
新的杯子对象吗?
解决方案
你需要用红宝石清除基础
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
推荐阅读
- java - 为什么java中方法的参数接受引用地址的副本?
- python - 限制多处理中使用的处理器数量
- excel - 更好更有效的选择(vlookup + 乘法的总和)
- json - 如何将 Swift 中的 HTTP POST 请求发送到 JSON?
- c# - 给定大小为 2048 的 RSA 公钥,如何仅使用内置的 .net 核心函数获取其模数和指数?
- ag-grid - Ag-grid 中的模态
- python-3.x - 无法使用属性名称作为键访问字典的成员
- python-3.x - 我们可以在 onevsrest 分类器中用作估计器的可用估计器有哪些?
- c# - Angular 脚本未绑定 json 响应
- pdf - 使用 UIPath 从 PDF 中刮取字段值数据