Why does map function mutate array of objects when operating on each element's attribute?Array#each vs. Array#mapHow to determine if Javascript array contains an object with an attribute that equals a given value?Which JavaScript Array functions are mutating?Difference between access to mapped objects in array through for cycle/for in cycleConvert object array to hash map, indexed by an attribute value of the ObjectWhy are two array clones are mimicking each other?copying an array of objects and then modifying the original without affecting the copyJs Array.prototype.map() happens to be mutable?Why is my Object array not keeping the object it is being assigned?How can i select a single value in array php?
How to compute the inverse of an operation in Q#?
How would one carboxylate CBG into its acid form, CBGA?
First occurrence in the Sixers sequence
Why are there no file insertion syscalls
Justifying Affordable Bespoke Spaceships
Can a character learn spells from someone else's spellbook and then sell it?
Make symbols atomic, without losing their type
Draw a symmetric alien head
In the US, can a former president run again?
In a list with unique pairs A, B, how can I sort them so that the last B is the first A in the next pair?
I just entered the USA without passport control at Atlanta airport
How to make all magic-casting innate, but still rare?
Freewill and rewarding dogs
If the mass of the Earth is decreasing by sending debris in space, does its angular momentum also decrease?
「捨ててしまう」why is there two て’s used here?
Is there any possible way to get these hearts as Adult Link?
What is the most suitable position for a bishop here?
Are there any individual aliens that have gained superpowers in the Marvel universe?
How is the idea of "girlfriend material" naturally expressed in Russian?
What is the maximum that Player 1 can win?
Is declining an undergraduate award which causes me discomfort appropriate?
How can the US president give an order to a civilian?
What is the highest power supply a Raspberry pi 3 B can handle without getting damaged?
I have found ports on my Samsung smart tv running a display service. What can I do with it?
Why does map function mutate array of objects when operating on each element's attribute?
Array#each vs. Array#mapHow to determine if Javascript array contains an object with an attribute that equals a given value?Which JavaScript Array functions are mutating?Difference between access to mapped objects in array through for cycle/for in cycleConvert object array to hash map, indexed by an attribute value of the ObjectWhy are two array clones are mimicking each other?copying an array of objects and then modifying the original without affecting the copyJs Array.prototype.map() happens to be mutable?Why is my Object array not keeping the object it is being assigned?How can i select a single value in array php?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have an array of objects:
class Person
attr_accessor :email
def initialize(email)
@email = email
end
end
array = [
Person.new('hello@gmail.com'),
Person.new('world@gmail.com')
]
I created a clone from the original array to perform map function, and then I mapped over each element to make its email attribute become uppercase:
clone = array.clone
clone.map obj
puts array.inspect # why is the original being mutated
puts clone.inspect
It mutates the original array. I have experimented with both dup
and clone
. and I get the same result. Why does map
mutate the objects when operating on each element's attribute?
arrays ruby mutable
add a comment |
I have an array of objects:
class Person
attr_accessor :email
def initialize(email)
@email = email
end
end
array = [
Person.new('hello@gmail.com'),
Person.new('world@gmail.com')
]
I created a clone from the original array to perform map function, and then I mapped over each element to make its email attribute become uppercase:
clone = array.clone
clone.map obj
puts array.inspect # why is the original being mutated
puts clone.inspect
It mutates the original array. I have experimented with both dup
and clone
. and I get the same result. Why does map
mutate the objects when operating on each element's attribute?
arrays ruby mutable
Never doputs foo.inspect
, as it is equivalent top foo
, and you should use the latter.
– sawa
Mar 25 at 6:26
2
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
@sawa how is that "equivalent"?puts foo.inspect
will print the object and returnnil
.p foo
will print the object (via inspect) and return the object.
– engineersmnky
Mar 25 at 15:01
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00
add a comment |
I have an array of objects:
class Person
attr_accessor :email
def initialize(email)
@email = email
end
end
array = [
Person.new('hello@gmail.com'),
Person.new('world@gmail.com')
]
I created a clone from the original array to perform map function, and then I mapped over each element to make its email attribute become uppercase:
clone = array.clone
clone.map obj
puts array.inspect # why is the original being mutated
puts clone.inspect
It mutates the original array. I have experimented with both dup
and clone
. and I get the same result. Why does map
mutate the objects when operating on each element's attribute?
arrays ruby mutable
I have an array of objects:
class Person
attr_accessor :email
def initialize(email)
@email = email
end
end
array = [
Person.new('hello@gmail.com'),
Person.new('world@gmail.com')
]
I created a clone from the original array to perform map function, and then I mapped over each element to make its email attribute become uppercase:
clone = array.clone
clone.map obj
puts array.inspect # why is the original being mutated
puts clone.inspect
It mutates the original array. I have experimented with both dup
and clone
. and I get the same result. Why does map
mutate the objects when operating on each element's attribute?
arrays ruby mutable
arrays ruby mutable
edited Mar 25 at 6:31
sawa
134k31217312
134k31217312
asked Mar 25 at 6:14
jinhejinhe
62
62
Never doputs foo.inspect
, as it is equivalent top foo
, and you should use the latter.
– sawa
Mar 25 at 6:26
2
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
@sawa how is that "equivalent"?puts foo.inspect
will print the object and returnnil
.p foo
will print the object (via inspect) and return the object.
– engineersmnky
Mar 25 at 15:01
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00
add a comment |
Never doputs foo.inspect
, as it is equivalent top foo
, and you should use the latter.
– sawa
Mar 25 at 6:26
2
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
@sawa how is that "equivalent"?puts foo.inspect
will print the object and returnnil
.p foo
will print the object (via inspect) and return the object.
– engineersmnky
Mar 25 at 15:01
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00
Never do
puts foo.inspect
, as it is equivalent to p foo
, and you should use the latter.– sawa
Mar 25 at 6:26
Never do
puts foo.inspect
, as it is equivalent to p foo
, and you should use the latter.– sawa
Mar 25 at 6:26
2
2
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
@sawa how is that "equivalent"?
puts foo.inspect
will print the object and return nil
. p foo
will print the object (via inspect) and return the object.– engineersmnky
Mar 25 at 15:01
@sawa how is that "equivalent"?
puts foo.inspect
will print the object and return nil
. p foo
will print the object (via inspect) and return the object.– engineersmnky
Mar 25 at 15:01
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00
add a comment |
1 Answer
1
active
oldest
votes
You cloned the array containing Person
references, but you did not change the array; you changed the Person
instances themselves. clone
is so-called "shallow clone", which copies only the receiver object, but none of the objects whose references it may contain.
In real-world logic: you took a piece of paper on which you wrote "Jenny, Timmy". Then you copied it to another piece of paper. You then took the first piece of paper, found the people it refered to, and gave them an apple. Then you took the second piece of paper, found the people on it, and wondered where their apples came from. But there's only one Timmy, only one Jenny: you give the first list's Jenny an apple, the second list's Jenny also has one.
If you want to clone something, clone Jenny.
array.map person
(Note that I didn't use clone.email.upcase!
. The reason is the same reason all over again: if you clone an object, they will both use the same string for email
. upcase!
changes that string, which would uppercase both clone's email and the original's email. Thus, we make a new email string for the clone.)
Things like this are best understood by stepping through the visualisation using this tool. However, the tool runs Ruby 2.2, which doesn't know about yield_self
; this code is equivalent:
array.map person
You could also write this, though it won't visualise as clearly:
array.map(&:clone).map
clone.email = clone.email.upcase
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332152%2fwhy-does-map-function-mutate-array-of-objects-when-operating-on-each-elements-a%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You cloned the array containing Person
references, but you did not change the array; you changed the Person
instances themselves. clone
is so-called "shallow clone", which copies only the receiver object, but none of the objects whose references it may contain.
In real-world logic: you took a piece of paper on which you wrote "Jenny, Timmy". Then you copied it to another piece of paper. You then took the first piece of paper, found the people it refered to, and gave them an apple. Then you took the second piece of paper, found the people on it, and wondered where their apples came from. But there's only one Timmy, only one Jenny: you give the first list's Jenny an apple, the second list's Jenny also has one.
If you want to clone something, clone Jenny.
array.map person
(Note that I didn't use clone.email.upcase!
. The reason is the same reason all over again: if you clone an object, they will both use the same string for email
. upcase!
changes that string, which would uppercase both clone's email and the original's email. Thus, we make a new email string for the clone.)
Things like this are best understood by stepping through the visualisation using this tool. However, the tool runs Ruby 2.2, which doesn't know about yield_self
; this code is equivalent:
array.map person
You could also write this, though it won't visualise as clearly:
array.map(&:clone).map
clone.email = clone.email.upcase
add a comment |
You cloned the array containing Person
references, but you did not change the array; you changed the Person
instances themselves. clone
is so-called "shallow clone", which copies only the receiver object, but none of the objects whose references it may contain.
In real-world logic: you took a piece of paper on which you wrote "Jenny, Timmy". Then you copied it to another piece of paper. You then took the first piece of paper, found the people it refered to, and gave them an apple. Then you took the second piece of paper, found the people on it, and wondered where their apples came from. But there's only one Timmy, only one Jenny: you give the first list's Jenny an apple, the second list's Jenny also has one.
If you want to clone something, clone Jenny.
array.map person
(Note that I didn't use clone.email.upcase!
. The reason is the same reason all over again: if you clone an object, they will both use the same string for email
. upcase!
changes that string, which would uppercase both clone's email and the original's email. Thus, we make a new email string for the clone.)
Things like this are best understood by stepping through the visualisation using this tool. However, the tool runs Ruby 2.2, which doesn't know about yield_self
; this code is equivalent:
array.map person
You could also write this, though it won't visualise as clearly:
array.map(&:clone).map
clone.email = clone.email.upcase
add a comment |
You cloned the array containing Person
references, but you did not change the array; you changed the Person
instances themselves. clone
is so-called "shallow clone", which copies only the receiver object, but none of the objects whose references it may contain.
In real-world logic: you took a piece of paper on which you wrote "Jenny, Timmy". Then you copied it to another piece of paper. You then took the first piece of paper, found the people it refered to, and gave them an apple. Then you took the second piece of paper, found the people on it, and wondered where their apples came from. But there's only one Timmy, only one Jenny: you give the first list's Jenny an apple, the second list's Jenny also has one.
If you want to clone something, clone Jenny.
array.map person
(Note that I didn't use clone.email.upcase!
. The reason is the same reason all over again: if you clone an object, they will both use the same string for email
. upcase!
changes that string, which would uppercase both clone's email and the original's email. Thus, we make a new email string for the clone.)
Things like this are best understood by stepping through the visualisation using this tool. However, the tool runs Ruby 2.2, which doesn't know about yield_self
; this code is equivalent:
array.map person
You could also write this, though it won't visualise as clearly:
array.map(&:clone).map
clone.email = clone.email.upcase
You cloned the array containing Person
references, but you did not change the array; you changed the Person
instances themselves. clone
is so-called "shallow clone", which copies only the receiver object, but none of the objects whose references it may contain.
In real-world logic: you took a piece of paper on which you wrote "Jenny, Timmy". Then you copied it to another piece of paper. You then took the first piece of paper, found the people it refered to, and gave them an apple. Then you took the second piece of paper, found the people on it, and wondered where their apples came from. But there's only one Timmy, only one Jenny: you give the first list's Jenny an apple, the second list's Jenny also has one.
If you want to clone something, clone Jenny.
array.map person
(Note that I didn't use clone.email.upcase!
. The reason is the same reason all over again: if you clone an object, they will both use the same string for email
. upcase!
changes that string, which would uppercase both clone's email and the original's email. Thus, we make a new email string for the clone.)
Things like this are best understood by stepping through the visualisation using this tool. However, the tool runs Ruby 2.2, which doesn't know about yield_self
; this code is equivalent:
array.map person
You could also write this, though it won't visualise as clearly:
array.map(&:clone).map
clone.email = clone.email.upcase
edited Mar 25 at 6:31
answered Mar 25 at 6:19
AmadanAmadan
138k13152203
138k13152203
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332152%2fwhy-does-map-function-mutate-array-of-objects-when-operating-on-each-elements-a%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Never do
puts foo.inspect
, as it is equivalent top foo
, and you should use the latter.– sawa
Mar 25 at 6:26
2
“you should use the latter”—says who?
– Aleksei Matiushkin
Mar 25 at 6:50
@sawa how is that "equivalent"?
puts foo.inspect
will print the object and returnnil
.p foo
will print the object (via inspect) and return the object.– engineersmnky
Mar 25 at 15:01
@engineersmnky I was not accurate. Their outputs are the same, and for the purpose in this context, they do not make difference.
– sawa
Mar 25 at 16:00