我有这样的哈希.
products = {199 =>['Shoes', 59.99], 211 =>['Shirts', 19.99], 245 =>['Hats', 25.99], 689 => ['Coats', 99.99], 712 => ['Beanies', 6.99]}
Run Code Online (Sandbox Code Playgroud)
它有一个项目编号=> [product, price]
.
我想在不使用注入方法的情况下总结所有价格.
有人可以帮我吗?
我有一个产品文件,列出了商品#,产品和价格.我想阅读这个文件,并将其初始化为哈希,项目#是关键,产品和价格是价值.这是我的档案
199, Shoes, 59.99
211, Shirts, 19.99
245, Hats, 25.99
689, Coats, 99.99
712, Beanies, 6.99
Run Code Online (Sandbox Code Playgroud)
我希望它看起来像这样.
products = {
199 =>['Shoes', 59.99],
211 =>['Shirts', 19.99],
245 =>['Hats', 25.99],
689 => ['Coats', 99.99],
712 => ['Beanies', 6.99]
}
Run Code Online (Sandbox Code Playgroud)
这就是我能提出的并不是它真正想要的东西.
products_file = File.open("files.txt")
products_hash = []
while ! products_file.eof?
product_hash = products_file.gets.chomp
print product_hash.split(', ')
end
Run Code Online (Sandbox Code Playgroud)
以下是我提出的输出:
["199", "Shoes", "59.99"]
["211", "Shirts", "19.99"]
["245", "Hats", "25.99"]
["689", "Coats", "99.99"]
["712", "Beanies", "6.99"]
Run Code Online (Sandbox Code Playgroud) 我想生成一个介于100和999之间的唯一随机数序列.我想确保没有生成两次数字,以确保每个数字都是唯一的.这就是我想出的.这是行不通的.当我运行它时,屏幕只是空白.谁能帮我?
products = {}
def random_key(products)
rand_key = rand(900) + 100
while products.has_key?(rand_key)
rand_key = rand(900) + 100
end
end
puts random_key(products)
Run Code Online (Sandbox Code Playgroud)