如果你想命名每個實例(所以使用散列而不是數組),你可以這樣做:
steaks = {}
["Select", "Choice", "Prime"].each do |grade|
# I think using a symbol as key in this case is nicer
steaks[grade.downcase.to_sym] = Steak.new(grade)
end
還是有點短/最佳使用地圖就像你問(支持從紅寶石2.1開始):
steaks = ["Select", "Choice", "Prime"].map{ |g|
[g.downcase.to_sym, new Steak(grade)]
}.to_h
另一種方法是創建一個Butcher
類抽象了這一切。
butcher = new Butcher.new
butcher.addNewSteak(Steak.new("Select"))
butcher.addNewSteak(Steak.new("Choice"))
butcher.addNewSteak(Steak.new("Prime"))
# Or added/created using a loop
["Select", "Choice", "Prime"].each do |grade|
butcher.addNewSteak(Steak.new(grade)
end
# Get a list of steaks
butcher.getAllSteaks()
# Get steak by grade
bucher.getSteakByGrade("Select")
# Get all steaks by grade greater than
bucher.getSteakGradeGT("Choice")
屠夫類的實施被故意遺漏。制定是爲了應對亞歷杭德羅·C的答案下提出的問題
哪兒了你期望「牛排」來自哪裏? – ndn
除了提供的答案,您可能會對Ruby中的並行賦值感興趣。'a,b,c = [1,2,3]'然後'a#=> 1','b#=> 2'和'c#=> 3'。 –