I am using Ruby on Rails 3 and I would like to initialize my class. In my case I need to set params[:name] ||= {} every time I use that class.
How to do that?
UPDATE I
Is it possible to simplify things using something like
class A
def initialize
params[:name] ||= {}
end
end
?
UPDATE II
I forgot to say that in my class I have to use that parameter as an hash:
class A
def initialize
# code to initialize params[:name] ||= {}
end
def action_name
params[:name][:ronda] = "Jack"
end
end
If I try to set params[:name][:ronda] without inizialize params[:name] ||= {}, I get an error. For this I have to initialize the class.
I the above code I can do
def action_name
params[:name] ||= {}
params[:name][:ronda] = "Jack"
end
and it will work, but since I have to use that for every action in the class, I would like to refractor code setting the params[:name] at once.
You can use the initialize function to set defaults:
class A def initialize @params = {name: {}} end def params @params end end A.new.params # {:name => {}}You can also default upon access this way:
class A def initialize @params = {} end def params @params[:name] ||= {} @params end end A.new.params # {:name => {}}The difference is that the first example adds the :name parameter upon creation (A.new) while the second example adds it upon access (A.new.params).