2012-03-05 20 views
136

Sono nuovo di Ruby e non so come aggiungere un nuovo elemento all'hash già esistente. Ad esempio, prima costruisco hash:Come aggiungere un nuovo elemento all'hash

hash = {:item1 => 1} 

dopo che un bisogno di aggiungere item2 così dopo questo devo hash come questo:

{:item1 => 1, :item2 =>2} 

Non so quale metodo fare in hash, qualcuno potrebbe aiutarmi?

+5

@ ИванБишевац In caso di dubbio, consultare [la documentazione] (http://ruby-doc.org/core-1.9.3/Hash .html # metodo-i-5B-5D-3D). –

risposta

225

Creare l'hash:

hash = {:item1 => 1} 

aggiunge un nuovo elemento ad esso:

hash[:item2] = 2 
25

E 'semplice come:

irb(main):001:0> hash = {:item1 => 1} 
=> {:item1=>1} 
irb(main):002:0> hash[:item2] = 2 
=> 2 
irb(main):003:0> hash 
=> {:item1=>1, :item2=>2} 
54

Se si desidera aggiungere nuovi elementi da un altro hash - utilizzare merge metodo:

hash = {:item1 => 1} 
another_hash = {:item2 => 2, :item3 => 3} 
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3} 

Nel vostro caso specifico potrebbe essere:

hash = {:item1 => 1} 
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2} 

ma non è consigliabile utilizzarlo quando dovresti aggiungere solo un elemento in più.

attenzione che merge sostituirà i valori con i tasti esistenti:

hash = {:item1 => 1} 
hash.merge({:item1 => 2}) # {:item1=>2} 

esattamente come hash[:item1] = 2

Inoltre si dovrebbe prestare attenzione che il metodo merge (ovviamente) non influenza il valore originale della variabile hash - restituisce un nuovo hash unito. Se si desidera sostituire il valore della variabile hash quindi utilizzare merge! invece:

hash = {:item1 => 1} 
hash.merge!({:item2 => 2}) 
# now hash == {:item1=>1, :item2=>2} 
1

Crea hash come:

h = Hash.new 
=> {} 

Ora inserire in hash come:

h = Hash["one" => 1] 
+1

Se provi a inserire più chiavi in ​​questo modo, vedrai che stai creando ogni volta un nuovo hash. Probabilmente non è quello che vuoi. E se questo è ciò che vuoi, non hai bisogno della parte di 'Hash.new' a prescindere, perché' Hash [] 'sta già creando un nuovo hash. – philomory

1
hash_items = {:item => 1} 
puts hash_items 
#hash_items will give you {:item => 1} 

hash_items.merge!({:item => 2}) 
puts hash_items 
#hash_items will give you {:item => 1, :item => 2} 

hash_items.merge({:item => 2}) 
puts hash_items 
#hash_items will give you {:item => 1, :item => 2}, but the original variable will be the same old one. 
14

hash.store (chiave, valore) - Memorizza una coppia chiave-valore in hash.

Esempio:

hash #=> {"a"=>9, "b"=>200, "c"=>4} 
hash.store("d", 42) #=> 42 
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42} 

Documentation

Problemi correlati