在 ruby 中排序和循环

Sorting and loops in ruby

这是一个程序,它要求用户输入有关宝石特征的信息,然后打印到屏幕上。诸如颜色、价格和名称之类的东西。我已经把它写到用户输入所有这些并打印出来的地方。我现在卡在我应该循环并允许用户输入任意数量的宝石的地方。就像如果 he/she 输入 3 种宝石那么它应该循环并允许用户输入 3 种宝石类型的特征。我还想按字母顺序对宝石名称的结果输出进行排序。赞赏

class GemStones
  # input variables
  name = ""
  color = ""
  price = 0
  gemstoneNumber = 0


  # output variable
  gemstoneNumber = 0

  # processing
  print "How many gemstones do you want to enter? "
  gemstoneNumber = gets

  print "What is the name of the gemstone? "
  name = gets

  print "What is the color of the gemstone? "
  color = gets

  print "What is the price of the gemstone? "
  price = gets



  puts " You entered #{gemstoneNumber} The name is #{name}, the color is #{color} and price is
  $ #{price}"



end

您首先不应将代码包装在 class 中。您的代码中没有 OOP,因此也不需要 class 。此外,gets returns 一个字符串,而对于 number 你可能需要一个整数。

这里是你的代码的[或多或少]ruby版本:

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

或者,您可以使用 class 而不是散列来存储宝石信息。


按名称对宝石进行排序:

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(及周围。)

你也可以试试这个。

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