ruby使用每个实例化类

时间:2016-12-08 16:10:49

标签: ruby

a = ["Select", "Choice", "Prime"]
a.each do |f|
    f.downcase = f.new
    f.grade = f
end

不是这样做的方法

select = Steak.new
select.grade = "Select"
choice = Steak.new
choice.grade = "Choice"
prime = Steak.new
prime.grade = "Prime"

是否有可能使用每个类实例化几个类似的类?

还是另一种方式?必须能够更有效地做到这一点。

5 个答案:

答案 0 :(得分:0)

当然可以:

<progress class="progress" value="10" max="100"></progress>
<i class="fa fa-check-circle-o"></i>

.fa {
    position: relative;
    z-index: 2;
    top: -35px;
    left: 50%;
}

答案 1 :(得分:0)

好的,足够简单:

int

然而,它看起来真的是等级是牛排的重要特征。也许它应该像这样构造函数的一部分?

grades = ["Select", "Choice", "Prime"]
steaks = grades.map do |grade|
  steak = Steak.new
  steak.grade = grade.downcase
  steak
end

我认为创建一个初始化方法可以作为读者的练习。

答案 2 :(得分:0)

如果你想为每个实例命名(所以使用哈希而不是数组),你可以这样做:

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

或者像你问的那样使用地图更短/最佳(支持从ruby-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")

Butcher课程的实施被故意排除在外。详细说明是对Alejandro C答案提出的问题的回应。

答案 3 :(得分:0)

做你要求的最简单的方法:

steaks = ["Select", "Choice", "Prime"].map do |grade|
  s = Steak.new
  s.grade = grade.downcase
  s
end

另一方面,我建议反对grade成为可变成员。可变性导致错误。如果gradeSteak的基本部分,则应在构造函数中对其进行初始化:

class Steak
  def initialize(grade)
    @grade = grade.downcase
  end
end

然后你的代码会更简单

steaks = ["Select", "Choice", "Prime"].map do |grade|
  Steak.new grade
end

答案 4 :(得分:0)

使用这种结构,你得到一个哈希,例如: :prime为关键字,Steak.new("Prime")为值。 它可以更容易地迭代你的所有牛排,如果你想要一个特定的牛排,只需使用steaks[:prime]

class Steak
  attr_reader :grade
  def initialize(grade)
    @grade = grade
  end

  def to_s
    format("Steak %s", grade)
  end
end

steaks = ["Select", "Choice", "Prime"].map{|grade| [grade.downcase.to_sym, Steak.new(grade)]}.to_h

p steaks
# {:select=>#<Steak:0x000000013e7000 @grade="Select">,
#  :choice=>#<Steak:0x000000013e6f60 @grade="Choice">,
#  :prime=>#<Steak:0x000000013e6ec0 @grade="Prime">}

puts steaks.values
# Steak Select
# Steak Choice
# Steak Prime

puts steaks[:select].grade # => "Select"

如果你真的想要牛排的3个独立变量:

select, choice, prime = ["Select", "Choice", "Prime"].map{|grade| Steak.new(grade)}