hasan's blog (বল্গ)

work for fun!!!

Archive for August 31st, 2007

damn simple!!!, define instance variables in ruby way

leave a comment »

i was creating a new class where a hash object will be passed with value and key. my class suppose to iterate for each key and value. and those key will be treated as the instance variable.

so the pretty simple job i did is the following lines of code block -

def initialize(p_params = {})
super()
unless p_params.empty?
p_params.each do |key, value|
eval %(
self.#{key} = value
)

end
end
end

surprisingly my instance variable declaration became soooooo simple and easy.

update:
i didn’t know that self.send(“#{key}=”, value) does the same job, obviously send is prefer way to do this job.

Written by nhm tanveer hossain khan

August 31, 2007 at 12:39 am

Posted in Ruby, tips