Search code examples
ruby-on-railsrubystring-interpolation

How to access Model attributes dynamically in a loop in ruby?


My model class:

class item
  attr_accessor :item_name
  attr_accessor :item_url
  attr_accessor :item_label
  .
  . 
end

when I want to assign the value for this attributes.Insted of assigning one by one i.eitem.item_name="abc".

I want to put all the attributes in loop with hardcoded name and assign form some other source.

['item_url','item_url','item_label'].each do |attr|
   item.attr=values from some other source #error on this line
   #or
   item."#{attr}"=values from some other source #error on this line
end

Both of them not working. Any Suggestions are welcome


Solution

  • You can do like this:

     item.send((attr + "="), values from some other source)
    

    or:

    hash = {}
    ['item_url','item_url','item_label'].each do |attr|
      hash[attr] = value
    end
    item.attributes = hash