From 36895bd90fe02dbbf2c8461dffb30eb25c7cf3e1 Mon Sep 17 00:00:00 2001 From: Attila Domokos Date: Thu, 21 Aug 2014 23:07:03 -0500 Subject: Replacing an each with reduce The functionality has not changed, but the code is more elegant by using `reduce` instead of `each`. This way no accumulator needs to be declared, no explicit return is needed. --- activemodel/lib/active_model/errors.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'activemodel/lib') diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index fc8034f9c7..f7126c1eb8 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -251,11 +251,9 @@ module ActiveModel # person.errors.to_hash(true) # => {:name=>["name cannot be nil"]} def to_hash(full_messages = false) if full_messages - messages = {} - self.messages.each do |attribute, array| - messages[attribute] = array.map { |message| full_message(attribute, message) } + self.messages.reduce({}) do |messages, (attribute, array)| + messages.merge!(attribute => array.map { |message| full_message(attribute, message) }) end - messages else self.messages.dup end -- cgit v1.2.3 From 1079bb6d7dafa975fbe6b56fbf8824c84e7fca17 Mon Sep 17 00:00:00 2001 From: Attila Domokos Date: Fri, 22 Aug 2014 08:08:12 -0500 Subject: Using `each_with_object` instead of `reduce` This way no new object allocation is taking place. Thanks @jeremy for the suggestion! --- activemodel/lib/active_model/errors.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activemodel/lib') diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index f7126c1eb8..1b46727351 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -251,8 +251,8 @@ module ActiveModel # person.errors.to_hash(true) # => {:name=>["name cannot be nil"]} def to_hash(full_messages = false) if full_messages - self.messages.reduce({}) do |messages, (attribute, array)| - messages.merge!(attribute => array.map { |message| full_message(attribute, message) }) + self.messages.each_with_object({}) do |(attribute, array), messages| + messages[attribute] = array.map { |message| full_message(attribute, message) } end else self.messages.dup -- cgit v1.2.3