["LCEOT"...">

Ruby Hash Interaction with Clicking an Array

So let's say I do the following:

lph = Hash.new([])       #=> {}
lph["passed"] << "LCEOT" #=> ["LCEOT"]
lph                      #=> {} <-- Expected that to have been {"passed" => ["LCEOT"]}
lph["passed"]            #=> ["LCEOT"]
lph["passed"] = lph["passed"] << "HJKL"
lph #=> {"passed"=>["LCEOT", "HJKL"]}

I am surprised by this. A few questions:

  • Why is it not installed until I enter the second string into the array? What happens in the background?
  • The larger the idiomatic ruby ​​way of saying. I have a hash, key, and value that I want to end in the array associated with the key. How to transfer a value to an array associated with a key in a hash for the first time. In all future uses of the key, I just want to add to the array.
+4
source share
2 answers

Ruby Hash.new documentation - , -, , ".

new (obj) → new_hash

... obj , .

- , , , , .

the_array = []
h = Hash.new(the_array)
h['foo'] << 1 # => [1]
# Since the key 'foo' was not found
# ... the default value (the_array) is returned
# ... and 1 is pushed onto it (hence [1]).
the_array # => [1]
h # {} since the key 'foo' still has no value.

, :

new {| hash, key | block} → new_hash

... , - . , .

:

h = Hash.new { |hash, key| hash[key] = [] } # Assign a new array as default for missing keys.
h['foo'] << 1 # => [1]
h['foo'] << 2 # => [1, 2]
h['bar'] << 3 # => [3]
h # => { 'foo' => [1, 2], 'bar' => [3] }
+6

, ?

; , .

?

, , :

lph = Hash.new([])       #=> {}

, [] , .

lph["passed"] << "LCEOT" #=> ["LCEOT"]

value = lph["passed"] #=> []
value << "LCEOT"      #=> ["LCEOT"]

, lph["passed"] [], , "LCEOT" [].

lph                  #=> {}

lph - Hash. Hash. - , lph.

lph["passed"]        #=> ["LCEOT"]

. , value << ["LCEOT"]. , lph , . [], ["LCEOT"]. .

lph["passed"] = lph["passed"] << "HJKL"

lph. , lph["passed"], ( "passed" - lph) "HJKL". ["LCEOT"], ["LCEOT", "HJKL"].

lph["passed"] << "HJKL" ["LCEOT", "HJKL"], lph["passed"].

Ruby

<<=:

>> lph = Hash.new { [] }
=> {}
>> lph["passed"] <<= "LCEOT"
=> ["LCEOT"]
>> lph
=> {"passed"=>["LCEOT"]}

, Hash, . , , , , .

+3
source

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


All Articles