Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 892
B Seven Avatar asked Oct 06 '12 19:10

B Seven


People also ask

What is new () in Ruby?

new , the class will create a new instance of itself. It will then, internally, call the method initialize on the new object. Doing so it will simply pass all the arguments that you passed to new on to the method initialize .

What is attr in Ruby?

The attr method creates an instance variable and a getter method for each attribute name passed as argument. An argument can be a Symbol or a String that will be converted to Symbol module Attr.

Is initialize a keyword in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.


2 Answers

You can just iterate over the keys and invoke the setters. I prefer this, because it will catch if you pass an invalid key.

class Foo   attr_accessor :name, :age, :email, :gender, :height    def initialize params = {}     params.each { |key, value| send "#{key}=", value }   end end  foo = Foo.new name: 'Josh', age: 456 foo.name  # => "Josh" foo.age   # => 456 foo.email # => nil 
like image 108
Joshua Cheek Avatar answered Oct 14 '22 03:10

Joshua Cheek


def initialize(params)   params.each do |key, value|     instance_variable_set("@#{key}", value)   end end 
like image 27
Zach Kemp Avatar answered Oct 14 '22 04:10

Zach Kemp