How to Add New Item to Hash

How to add new item to hash

Create the hash:

hash = {:item1 => 1}

Add a new item to it:

hash[:item2] = 2

Append key/value pair to hash with in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

How do I append a key value pair to an existing hash in Ruby?

There are 3 ways:

.merge(other_hash) Returns a new hash containing the contents of other_hash and the contents of hsh.

hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}

.merge!(other_hash) Adds the contents of other_hash to hsh.

hash = { a: 1 }
puts hash.merge!({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}

And most efficient way is to modify existing hash, setting new values directly:

hash = { a: 1 }
hash[:b] = 2
hash[:c] = 3
puts hash # => {:a=>1, :b=>2, :c=>3}

Corresponding Benchmarks for these methods:

       user     system      total        real
0.010000 0.000000 0.010000 ( 0.013348)
0.010000 0.000000 0.010000 ( 0.003285)
0.000000 0.000000 0.000000 ( 0.000918)

How to add to an existing hash in Ruby

If you have a hash, you can add items to it by referencing them by key:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'

Here, like [ ] creates an empty array, { } will create a empty hash.

Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.

Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.

It's important to keep in mind that the specific nature of a key of a hash often matters:

hash = { :a => 'a' }

# Fetch with Symbol :a finds the right value
hash[:a]
# => 'a'

# Fetch with the String 'a' finds nothing
hash['a']
# => nil

# Assignment with the key :b adds a new entry
hash[:b] = 'Bee'

# This is then available immediately
hash[:b]
# => "Bee"

# The hash now contains both keys
hash
# => { :a => 'a', :b => 'Bee' }

Ruby on Rails confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.

You can also index on nearly anything, including classes, numbers, or other Hashes.

hash = { Object => true, Hash => false }

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil

Hashes can be converted to Arrays and vice-versa:

# Like many things, Hash supports .to_a
{ :a => 'a' }.to_a
# => [[:a, "a"]]

# Hash also has a handy Hash[] method to create new hashes from arrays
Hash[[[:a, "a"]]]
# => {:a=>"a"}

When it comes to "inserting" things into a Hash you may do it one at a time, or use the merge method to combine hashes:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}

Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method:

hash = { :a => 'a' }

# Returns the result of hash combined with a new hash, but does not alter
# the original hash.
hash.merge(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Nothing has been altered in the original
hash
# => {:a=>'a'}

# Combine the two hashes and store the result in the original
hash.merge!(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Hash has now been altered
hash
# => {:a=>'a',:b=>'b'}

Like many methods on String and Array, the ! indicates that it is an in-place operation.

How to add new keys and values to existing hash table in R?

The documentation for the hash package provides a number of syntax varieties for adding new elements to a hash:

h <- hash()
.set( h, keys=letters, values=1:26 )
.set( h, a="foo", b="bar", c="baz" )
.set( h, c( aa="foo", ab="bar", ac="baz" ) )

The first .set option would seem to be the best for bulk inserts of key value pairs. You would only need a pair of vectors, ordered in such a way that the key value representation is setup the way you want.

Insert element at the beginning of Ruby Hash?

response = {aa: 'aaa', bb: 'bbb'}
new_response = {new: 'new_value'}.merge(response)
# => {:new=>"new_value", :aa=>"aaa", :bb=>"bbb"}

Add a new item to a dictionary in Python

default_data['item3'] = 3

Easy as py.

Another possible solution:

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.

Adding values to array hash ruby at a specific position

We are given three objects.

jsonResponse = {
:json=>{
"reply"=>[
{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"},
{"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"},
{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}
]
},
:status=>200
}

key_value_pair_to_add = { 'new_value'=>'new_result' }
key_to_precede = 'location'

We then modify jsonResponse as follows.

keys_to_shift = jsonResponse[:json]['reply'][0].keys.
drop_while { |k| k != key_to_precede }
#=> ["location", "score"]
jsonResponse[:json]['reply'].each do |h|
h.update('new_value'=>'new_result')
keys_to_shift.each { |k| h.update(k=>h.delete(k)) }
end
jsonResponse
#=> {
# :json=>{
# "reply"=>[
# {"person"=>"abc", "roll_no"=>"1234", "new_value"=>"new_result",
# "location"=>"loc1", "score"=>"1"},
# {"person"=>"def", "roll_no"=>"1235", "new_value"=>"new_result",
# "location"=>"loc2", "score"=>"2"},
# {"person"=>"fgh", "roll_no"=>"1236", "new_value"=>"new_result",
# "location"=>"loc3", "score"=>"3"}
# ]
# },
# :status=>200
# }

See Hash#update (aka merge!) and Hash#delete.

h.delete('location')

removes the key-value pair 'location'=>'locX' from h and returns locX, after which

h.update('location'=>'locX')

returns that key-value pair to the end of the hash. This is repeated for each key in keys_to_shift.

Is possible to insert a new item in the middle of a hash and have it reindex?

Try using an Array, as hashes are not inherently ordered. Ruby's Array.insert lets you specify where to insert your new objects (http://www.ruby-doc.org/core/classes/Array.html#M000230), and using your example above, we get:

arr = [{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"},
{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"},
{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"}]

arr.insert(2, {"some hash"})

[{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"},
{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"},
{"some hash"},
{":amount_paid"=>"100.00", ":date_paid"=>"2/20/2009"}]

You can then iterate over the indices and maintain your desired order while adding to it.

Add new items to multidimensional Ruby hash in loop

This seems pretty straightforward. No need to loop over all of the key/value pairs looking for :customers when we can access it directly.

if bannerhash.has_key?(:customers)
bannerhash[:customers].each { |h|
h[:image][:newitem] = "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside- table_3300x.jpg?v=1637223489"
}
else
puts "banners not found"
end


Related Topics



Leave a reply



Submit