I'm creating a Ruby program that ask how many computers you want and its has arrays for computers, monitors, and a free item. I want to add a cost to each of the arrays. If I could add a value to each item within the array that would be great but may be too complicated for me to understand as a beginner.
what I have thus far:
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", " 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()
I think you can try this first. Use Hash
to group the price and the name information of products together first and then extract the data you want.
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
After implementing this, you can let user input the model name they want instead of the number of computers. You can use find
to find the element they want in the products' arrays, for example,
computer_types.find { |c| c[:name] == 'HP Pro' }
# => {:name=>"HP Pro", :price=>200}