How to cleanly initialize attributes in Ruby with new?

前端 未结 7 620
夕颜
夕颜 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 05:00

    Why not just explicitly specify an actual list of arguments?

    class Foo
      attr_accessor :name, :age, :email, :gender, :height
    
      def initialize(name, age, email, gender, height)
        @name = name
        @age = age
        @email = email
        @gender = gender
        @height = height
      end
    end
    

    This version may be more lines of code than others, but it makes it easier to leverage built-in language features (e.g. default values for arguments or raising errors if initialize is called with incorrect arity).

提交回复
热议问题