一次更改数组的所有项目

时间:2012-11-29 12:41:07

标签: ruby arrays ruby-on-rails-3 performance postgresql

我想知道是否有办法避免循环遍历列表中的所有项目以访问相同的属性。

people = [John, Bob, Dave, Eric]

每个都有一个数字属性(即John.num

所以而不是people.map{|person| person.num =10}

我可能会people.[...some magic..].num = 10

通过所有的循环似乎是浪费......可能是SQL或类似的

2 个答案:

答案 0 :(得分:3)

如果人们是ActiveRecord模型,您可以使用update_all方法

Person.update_all("num=10")

答案 1 :(得分:0)

我的情况是一个无AR对象,你可以使用Monkey Patched Array但我认为这是可怕的方式......我鼓励你不这样做!!

class Person
  def num=(value)
    @num = value
  end
  def num
    @num
  end
end

class Array

  def num value = 10
    self.each do |element|
      element.__send__(:num=, 10) if element && element.respond_to?(:num)
    end
  end

end

begin
  john = Person.new
  bob  = Person.new
  [john, bob].num
  puts "john.num => #{john.num}"
end
相关问题