Initialize with multiple instance variables as passed array/hash elements

Hey there,

This is what I am trying to achieve;

I would like to create an object with multiple instance variables (passed as an array) and initialize.

here is my initializer;

...    
        attr_accessor :fn

        def initialize(*fn)
          @fn = fn
        end
...

loaded_file = YAML.load_file('example.yml')
fo = MyClass.new(file_load.values.map(&:to_s))
fo.some_method

However in this approach my instance variable is created only once and gets;

["[\"first_instance_var\", \"second_instance_var\", \"third_instance_var\"]"]

My example.yml looks like this;

filename:
  - first_instance_var
  - second_instance_var
  - third_instance_var

My point is to get something like;

["first_instance_var", "second_instance_var", "third_instance_var"]

So that I can iterate with instance methods for each item.

Thanks in advance,

Found the workaround as below;

  file_payload = YAML.load_file('./example.yml')

  file_payload.values.flatten.map do |v|
    pay = MyConfig.new(v)
    pay.my_method1
    pay.my_method2
  end

Please let me know if you have a nicer approach.

Thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs