如何为 Ruby 中的每个数组分配货币值?

问题描述 投票:0回答:1

我正在创建一个 Ruby 程序,询问您想要多少台计算机,它有计算机、显示器和免费物品的数组。我想为每个数组添加成本。如果我可以为数组中的每个项目添加一个值,那就太好了,但对于初学者来说可能太复杂而无法理解。

到目前为止我所拥有的:

def computer_order()
    puts "how many computers with monitors would you like today?"
    number = gets.chomp
    number = number.to_i
    number
end

def monitor_and_computer()
    computer_type = ["Dell Inspiron", "HP Pro", "Acer Vero", "Lenovo Ideacentre", "Dell Optiplex", "HP Envy"]
    monitor_type = ["Dell 27' Curved", "Viewsonic 22' Flat", "LG 24' Flat", "Samsung 27' Curved", "Spectre 27' Flat", "MSI 31.5' Curved"]
    free_item = ["250G Thumb drive", "Declan's Shop T-Shirt", "25$ Steam Gift Card"]
    cost = 600

    number_of_computers = computer_order()
    number_of_computers = number_of_computers.to_i
    total = (number_of_computers * cost)
    total = total.to_s

    number_of_computers.times do 
        puts "One computer is  " +  computer_type.sample + ", " + monitor_type.sample + ", " + free_item.sample
    end 
       puts "Your total is: $" + total
end
    
    monitor_and_computer()
ruby
1个回答
0
投票

我想你可以先尝试一下。先用

Hash
将价格和商品名称信息分组到一起,然后提取出你想要的数据。

def computer_order
  puts "how many computers with monitors would you like today?"
  number = gets.chomp
  number = number.to_i
  number
end

def monitor_and_computer
  computer_types = [
    {
      name: "Dell Inspiron", 
      price: 100
    },
    {
      name: "HP Pro", 
      price: 200
    },
    {
      name: "Acer Vero", 
      price: 300
    },
    {
      name: "Lenovo Ideacentre", 
      price: 400
    },
    {
      name: "Dell Optiplex", 
      price: 500
    },
    {
      name: "HP Envy",
      price: 600
    }
  ]
  monitor_types = [
    {
      name: "Dell 27' Curved", 
      price: 200
    },
    {
      name: "Viewsonic 22' Flat", 
      price: 300
    },
    {
      name: "LG 24' Flat", 
      price: 400
    },
    {
      name: "Samsung 27' Curved", 
      price: 500
    },
    {
      name: "Spectre 27' Flat", 
      price: 600
    },
    {
      name: "MSI 31.5' Curved",
      price: 700
    }
  ]
  free_items = ["250G Thumb drive", "Declan's Shop T-Shirt", "25$ Steam Gift Card"]

  total = 0
  number_of_computers = computer_order
  number_of_computers.times do
    computer = computer_types.sample
    monitor = monitor_types.sample
    free_item = free_items.sample

    total += computer[:price] + monitor[:price]
    puts "One computer is #{computer[:name]}, #{monitor[:name]}, #{free_item}"
  end
  puts "Your total is: $#{total}"
end
    
monitor_and_computer

实现此功能后,您可以让用户输入他们想要的型号名称,而不是计算机的数量。您可以使用

find
在产品数组中查找所需的元素,例如,

computer_types.find { |c| c[:name] == 'HP Pro' }
# => {:name=>"HP Pro", :price=>200}
© www.soinside.com 2019 - 2024. All rights reserved.