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
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.
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.
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)
Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.
You can use instance_variable_set
like this:
params.each do |key, value|
self.instance_variable_set("@#{key}".to_sym, value)
end
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With