Nick Ginanto
Nick Ginanto

Reputation: 32130

Change all items of an array at once

I wonder if there is a way of avoiding looping through all items of a list to access the same attribute.

people = [John, Bob, Dave, Eric]

with each have a number attribute (i.e. John.num)

so instead of people.map{|person| person.num =10}

I might do people.[...some magic..].num = 10

It just seems a waste to loop through all.. maybe with SQL or similar

Upvotes: 0

Views: 117

Answers (2)

Joel AZEMAR
Joel AZEMAR

Reputation: 2526

I case are a none AR Object, You can Monkey Patched Array but i think it's HORRIBLE way... I encourage you don't do that !!

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

Upvotes: 0

alony
alony

Reputation: 10823

If people is an ActiveRecord model, you can use update_all method

Person.update_all("num=10")

Upvotes: 3

Related Questions