rubyobjectnew-operatorruby-1.9.3

How to cleanly initialize attributes in Ruby with new?


class Foo
  attr_accessor :name, :age, :email, :gender, :height

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

This seems like a silly way of doing it. What is a better/more idiomatic way of initalizing objects in Ruby?

Ruby 1.9.3


Solution

  • def initialize(params)
      params.each do |key, value|
        instance_variable_set("@#{key}", value)
      end
    end