Search code examples
ruby-on-railsrubyrefactoring

A better method to iterate over an array and object attributes?


(Edit:Now i just use ChatGPT for coding stuff... 1000x better than SO policy and moderators)

I found a solution that works, but i did some heavy copy/paste of blocks and there is only the params of the instance which changes (myobject.red, myobject.blue, myobject.yellow ). I try to refactor this method. There is an instance of Myobject, I need to push data in each parameter. I think it exist an elegant solution somewhere.

To create a set of data, i iterate over an array. Each result of the array needs to be pushed in the corresponding parameter of the instance. Thanks

class Myobject
 def initialize
  @blue = blue
  @red = red
  @yellow = yellow
 end
end

def mymethod
  param = ['foo','bar','jaa']
  
  param.each { |param|
    case param
    when 'foo'
      data = collect_method
      myobject.blue.push(data)
    when 'bar'
      data = collect_method
      myobject.red.push(data)
    when 'jaa'
      data = collect_method
      myobject.yellow.push(data)
    end
  end
end

Solution

  • def mymethod
      params = {'foo'=>:blue,'bar'=>:red,'jaa'=>:yellow}
      
      params.each do |k,v|
        my_object.send(v).push(collect_method(k))
      end
    end
    

    where collect_method is another method in Myobject class