Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Ruby can I automatically populate instance variables somehow in the initialize method?

in Ruby can I automatically populate instance variables somehow in the initialize method?

For example if I had:

class Weekend
  attr_accessor :start_date, :end_date, :title, :description, :location

  def initialize(params)
    # SOMETHING HERE TO AUTO POPULATE INSTANCE VARIABLES WITH APPROPRIATE PARAMS
  end

end
like image 959
Greg Avatar asked Mar 07 '12 07:03

Greg


People also ask

What does initialize method do in Ruby?

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.

Do you need to initialize variables in Ruby?

Ruby Class Variables Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error.

How do you declare an instance variable in Ruby?

The ruby instance variables do not need a declaration. This implies a flexible object structure. Every instance variable is dynamically appended to an object when it is first referenced. An instance variable belongs to the object itself (each object has its own instance variable of that particular class)

Can a Ruby module have instance variables?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.


2 Answers

You can use instance_variable_set like this:

params.each do |key, value|
  self.instance_variable_set("@#{key}".to_sym, value)
end
like image 55
Mischa Avatar answered Oct 20 '22 01:10

Mischa


To keep things simple:

class Weekend
  attr_accessor :start_date, :end_date, :title, :description, :location

  def initialize(params)
    @start_date = params[:start_date] # I don't really know the structure of params but you have the idea
    @end_date   = params[:end_date]
  end
end

You could do something smarter with a twist of metaprogramming but is this really necessary?

like image 32
apneadiving Avatar answered Oct 19 '22 23:10

apneadiving