0

Imagine this ruby code:

class Class1
  def initialize( par1: 1, par2: 2, par3: 3)
    @par1 = par1
    @par2 = par2
    @par3 = par3
  end
end

p Class1.new ##<Class1:0x00000002e5c930 @par1=1, @par2=2, @par3=3>
p Class1.new(par1: 'one', par2: 'two', par3: 'three') ##<Class1:0x00000002de0308 @par1="one", @par2="two", @par3="three">

How can I simplify the definition of the variables?

I found a solution with local_variables and instance_variable_set:

class Class2
  def initialize( par1: 1, par2: 2, par3: 3)
    local_variables.each{|local|
      #define attribute
      var = instance_variable_set("@#{local}", binding.local_variable_get(local))
    }
  end
end

p Class2.new ##<Class2:0x00000002e5c930 @par1=1, @par2=2, @par3=3>
p Class2.new(par1: 'one', par2: 'two', par3: 'three') ##<Class2:0x00000002de0308 @par1="one", @par2="two", @par3="three">

But is there an easier way?

knut
  • 27,320
  • 6
  • 84
  • 112
  • 1
    Using metaprogramming here is asking for trouble. Your trivial case is the exception, not the rule. If you have a class like this where you really don't care, it's just for storing data, use `OpenStruct` as a base class and call `super`. That's an implementation you can trust and it takes one line of code. – tadman Dec 07 '16 at 21:31
  • @tadman Thanks for the duplicate detection. I searched for a similar question but didn't find this question. Now you detected a nearly similar question. Actually I'm beginning a new project with many parameters and I wanted to research in different directions. OpenStruct will be one option. – knut Dec 07 '16 at 22:05
  • It's a pattern that's fairly common, but not so common there's an idiomatic way of doing it. Hope you find the right fit. – tadman Dec 07 '16 at 22:53

0 Answers0