这是一个程序,要求用户输入有关宝石特性的信息,然后将其打印到屏幕上。诸如颜色,价格和名称之类的东西。我已经将它写成扩展,用户可以输入所有这些内容并打印出来。现在卡在了我应该循环播放的位置,并使用户可以输入任意数量的宝石。就像他/她输入3颗宝石一样,它应该循环播放并允许用户输入3种宝石类型的特征。我还想按字母顺序对宝石名称的结果输出进行排序。赞赏
enterprise distribution profile
答案 0 :(得分:1)
首先不要将代码包装在class
中。您的代码中没有OOP,因此也不需要该类。另外,gets
返回一个字符串,而对于number
,您可能需要一个整数。
这将是代码的[或多或少]红宝石版本:
print "How many gemstones do you want to enter? "
# ⇓⇓⇓⇓⇓ get rid of trailing CR/LF
# ⇓⇓⇓⇓ convert to integer
gemstoneNumber = gets.chomp.to_i
gemstones =
1.upto(gemstoneNumber).map do |i|
puts
puts "Please enter data for the gemstone ##{i}:"
print "What is the name of the gemstone? "
name = gets.chomp # shave the trailing CR/LF off
print "What is the color of the gemstone? "
color = gets.chomp
print "What is the price of the gemstone? "
price = gets.chomp.to_f # convert to float
# in Ruby we normally use hashes to store
# the named values
{name: name, color: color, price: price}
end
puts "You entered #{gemstoneNumber} gemstones. They are:"
gemstones.each do |gemstone|
puts "Name: #{gemstone[:name]}. " \
"Color: #{gemstone[:color]}. " \
"Price: $#{gemstone[:price]}."
end
或者,您可以使用类而不是哈希来存储宝石信息。
按名称对宝石进行排序:
puts "You entered #{gemstoneNumber} gemstones. They are:"
# ⇓⇓⇓⇓⇓⇓⇓ HERE
gemstones.sort_by { |gemstone| gemstone[:name] }.each do |gemstone|
puts "Name: #{gemstone[:name]}. " \
"Color: #{gemstone[:color]}. " \
"Price: $#{gemstone[:price]}."
end
关于枚举的好的文档可以在官方的ruby文档中找到:https://ruby-doc.org/core/Enumerable.html#method-i-sort_by(及其周围)。
答案 1 :(得分:0)
您也可以尝试。
def gem_stones num
@gem_stones = []
num.times do |a|
print "Enter the name of gemstone #{a+1} "
name=gets.chomp
print "Enter the color of gemstone #{a+1} "
color = gets.chomp
print "Enter the price of gemstone #{a+1} "
price = gets.chomp.to_f
@gem_stones.push({name: name, color: color, price: price})
end
puts @gem_stones.sort_by {|a| a[:name]}.map{|gem| "Name: #{gem[:name]}, Color: #{gem[:color]}, Price: #{gem[:price]}"}.join("\n")
end
puts "Ener the number of gem stones you want to enter?"
num = gets.to_i
gem_stones num