How does this ruby ​​fragment work?

Riddle:

something = {}
another = something
('a'...'f').each do |x|
  puts "another = #{another} and x= #{x} and something = #{something}"
  another = (another[x] ||= {})
end
puts something

Conclusion:

=>another = {} and x= a and something = {}
=>another = {} and x= b and something = {"a"=>{}}
=>another = {} and x= c and something = {"a"=>{"b"=>{}}}
=>another = {} and x= d and something = {"a"=>{"b"=>{"c"=>{}}}}
=>another = {} and x= e and something = {"a"=>{"b"=>{"c"=>{"d"=>{}}}}}

Now, at first glance, it would seem that the “other” and “something” point to the same hash object, but if that were the case, then the output of the “other” would be “something”. So, how is the "something" variable not an empty hash?

+4
source share
2 answers

In Ruby, an entire object and all objects are passed using pointers (there are exceptions, but they do not apply here). When you do

something = {}
another = something

one Hash object is created, and both variables point to the same object. When you do

another[x] ||= {}

Hash, Hash, another.

old_hash = another
new_hash = {}
old_hash[x] = new_hash
another = new_hash

: . , another () . , old_hash , (.. another) old_hash. something .

:

x = {}
y = {}
z = {}
x["a"] = y
y["b"] = z
z["c"] = {}
puts x
# {"a"=>{"b"=>{"c"=>{}}}}

, .

+6

, , , "" "-" -, , "" "-".

something another . another another = (another[x] ||= {}). , something.object_id another.object_id.

another {}

,

another = (another[x] ||= {})

another , (another[x] ||= {}), {}, another {}

, , , , another, another something .

something = {}
another = something
('a'...'f').each do |x|
  puts "another = #{another} and x= #{x} and something = #{something}"
  another[x] ||= {}  ## Change to this
end
puts something

:

another = {} and x= a and something = {}
another = {"a"=>{}} and x= b and something = {"a"=>{}}
another = {"a"=>{}, "b"=>{}} and x= c and something = {"a"=>{}, "b"=>{}}
another = {"a"=>{}, "b"=>{}, "c"=>{}} and x= d and something = {"a"=>{}, "b"=>{}, "c"=>{}}
another = {"a"=>{}, "b"=>{}, "c"=>{}, "d"=>{}} and x= e and something = {"a"=>{}, "b"=>{}, "c"=>{}, "d"=>{}}
 => "a"..."f" 
2.1.0 :265 >     puts something
{"a"=>{}, "b"=>{}, "c"=>{}, "d"=>{}, "e"=>{}}
+2
source

Source: https://habr.com/ru/post/1539285/


All Articles