根据用户输入循环创建
Looping a creation based on user input
我正在创建一种算法,根据杯子的半径长度对杯子进行排序。输入将是
2
red 10
green 7
输出为
green
red
我的方法是看到第一个输入是 2 我将不得不创建 2 个具有颜色和半径属性的 Cup。如此处所示:
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
我在尝试访问 Cup.number_of_cups 时收到 undefined method
错误。我的问题是,例如,如果我输入 3
那么我会有 3
个新的杯子对象?
你需要通过 ruby
清除基础
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
我正在创建一种算法,根据杯子的半径长度对杯子进行排序。输入将是
2
red 10
green 7
输出为
green
red
我的方法是看到第一个输入是 2 我将不得不创建 2 个具有颜色和半径属性的 Cup。如此处所示:
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
我在尝试访问 Cup.number_of_cups 时收到 undefined method
错误。我的问题是,例如,如果我输入 3
那么我会有 3
个新的杯子对象?
你需要通过 ruby
清除基础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