Answer by Stefan for instance_variable_set in constructor
Instead of creating instance variables dynamically, you could use attr_accessor to declare the available instance variables and just call the setters dynamically: class Foo attr_accessor :bar, :baz,...
View ArticleAnswer by georgebrock for instance_variable_set in constructor
Diagnosing the problem What you're doing here is a fairly simple example of metaprogramming, i.e. dynamically generating code based on some input. Metaprogramming often reduces the amount of code you...
View ArticleAnswer by sawa for instance_variable_set in constructor
When you need to do such thing, the inventory of the parameters varies. In such case, there is already a handy structure within Ruby (as well as most modern languages): array and hash. In this case,...
View ArticleAnswer by Chris McCauley for instance_variable_set in constructor
Answers to this question are always going to be based on someone's personal opinion so here's mine. Clarity v Brevity If you cannot know the set of options ahead of time then you have no real choice...
View Articleinstance_variable_set in constructor
I've made a constructor like this: class Foo def initialize(p1, p2, opts={}) #...Initialize p1 and p2 opts.each do |k, v| instance_variable_set("@#{k}", v) end end end I'm wondering if it's a good...
View Article