How to cleanly initialize attributes in Ruby with new?

前端 未结 7 604
夕颜
夕颜 2020-12-06 04:17
class Foo
  attr_accessor :name, :age, :email, :gender, :height

  def initalize params
    @name = params[:name]
    @age = params[:age]
    @email = params[:email]         


        
7条回答
  •  遥遥无期
    2020-12-06 04:53

    Foo = Struct.new(:name, :age, :email, :gender, :height)
    

    This is enough for a fully functioning class. Demo:

    p Foo.class # Class
    
    employee = Foo.new("smith", 29, "smith@foo.com", "m", 1.75) #create an instance
    p employee.class # Foo
    p employee.methods.sort # huge list which includes name, name=, age, age= etc
    

提交回复
热议问题