Re: strange thing w/ array.map

Clem Rock
Thu, 25 Jan 2007 19:39:44 -0000

Chris,

   Thanks for your help - this is great.

Ruby does things I never expect - in the best of ways.

Cheers!




Chris Hall wrote:
> 2 things are going on here
>
> 1) i don''t believe you are getting back what you think you are
getting
> back from .map
> 2) the entity you are working with in your block is the actual entity,
> not a copy.  so you are basically overwriting your original array of
> entities
>
> .map returns a new array based on whatever it is you do in within the
> block
>
> [1,2,3].map { |x| x*3 } #=> [3,6,9]
>
> in your case the last statement in the block is
>
> entity.title += " (#{entity.status_title})"
>
> so your block is going to return whatever that evaluates to, not the
> entity object you are expecting.
>
> in addition, your block is actually overwriting all the values of the
> @entities objects you are passing in.  if you were to compare the
> titles of the @entities objects before and then after .map is called,
> you''re going to see that they are different.
>
> ex:
>
> class Thing
>   attr_accessor :foo
> end
>
> a = Thing.new
> a.foo = "abc"
> b = Thing.new
> b.foo = "xyz"
>
> x = [a,b].map { |c| c.foo += " modified" }
> a.foo # => "abc modified"
> b.foo # => "xyz modified"
> x = ["abc modified", "xyz modified"] # you expected
this to be an
> array of Thing objects
>
> if you do want to overwrite the attributes of your objects, just use
> .each
>
> @entities.each do |entity|
>   ...
> end


--
Posted via http://www.ruby-forum.com/.