1

See this IRB code :

2.6.6 :107 > h = {}
 => {} 
2.6.6 :108 > a = []
 => [] 
2.6.6 :109 > h["name"] = "hans"
 => "hans" 
2.6.6 :110 > a << h
 => [{"name"=>"hans"}] 
2.6.6 :111 > h["name"] = "paul"
 => "paul" 
2.6.6 :112 > a
 => [{"name"=>"paul"}] 
2.6.6 :113 > 

But this is not that what I want, when I overwrite the h Hash, I don't want to overwrite the already added value to the array ! ! !

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Sven Kirsten
  • 478
  • 1
  • 8
  • 27
  • 1
    What do you want? If you want a copy of the hash, then use `a << h.clone`. – ggorlen Oct 13 '20 at 15:01
  • Do you want `a #=> [{"name"=>"hans"}, {"name"=>"paul"}]`? When you give an example, you should always show the desired return value. It's also helpful to readers if you exclude the prompts (e.g., `2.6.6 :112 >`). Doing so makes what's left easier to read and allows readers to copy and paste your code without have to edit-out the the bumph. – Cary Swoveland Oct 13 '20 at 19:14
  • Thanks ggorlen - the h.clone is exact what I was looking for. But why RUBY handles Hashes and Arrray as REFERENCES not as COPY ? – Sven Kirsten Oct 14 '20 at 07:00

1 Answers1

0

Perhaps you wanted this:

2.6.6 :107 > h = {}
=> {} 
2.6.6 :108 > a = []
=> [] 
2.6.6 :109 > h["name"] = "hans"
=> "hans" 
2.6.6 :110 > a << h.clone
=> [{"name"=>"hans"}] 
2.6.6 :111 > h["name"] = "paul"
2.6.6 :112 > a
=> [{"name"=>"hans"}] 
Viktor Ivliiev
  • 1,015
  • 4
  • 14
  • 21