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 item to hash
Create the hash:
hash = {:item1 => 1}
Add a new item to it:
hash[:item2] = 2
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)
Append key/value pair to hash with in Ruby
There is merge!
.
h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
Append multiple new values to existing hash key in Ruby
Use push
:
my_hash["paths"].push("new path", "an other new path")
Demo
How to add a value to an existing hash without a key
The common solution is to simply use the value as a key. Hence:
value = "xxx"
hash[value] = 1
This way, you clearly document that the actual values (all 1
) of this particular hash are of no use, and you will get de-duplicated values. Hash
will do the usual hashing internally, you don't need to worry about it at all.
I use 1
as value here, but the actual value is completely irrelevant. I don't use nil
as that is the default return value of hash[nonexistant_value]
.
If your values are more complex, check out http://docs.ruby-lang.org/en/2.0.0/Hash.html for specifics about them.
How to insert a new hash into existing hash in ruby
I guess you want this:
r = [] << p << q
# or r = [p, q]
# either way you'll get:
# [ {"name"=>"VELLORE", "subdistrict"=>{"WANDIWASH"=>"4183"}},
# {"name"=>"TRICHI", "subdistrict"=>{"WANDIWASH"=>"1234"}} ]
This way you will have an array
with 2 hashes
.
Ruby add a nested key to an existing hash
You initialize the hash entry to 0
. You can't index the number 0
.
If you want the value at the hash to be an object then you should have each hash entry be a new hash { dollar: 0 }
, one way being:
> totals = Hash.new { |hash, key| hash[key] = { dollar: 0 } }
> totals[:foo][:dollar] += 50
> totals
=> { :foo => { :dollar => 50 } }
> totals[:foo][:dollar] += 50
> totals[:bar][:dollar] += 10
> totals
=> { :foo => { :dollar => 100 }, :bar => { :dollar => 10 } }
Add to existing hash inside of a class ruby
Replace the following line
@records = { "#{file}" => { :time => "#{time}", :rc => "#{rc}", :host => "#{host}", :ip => "#{ip}" } }
with
@records["#{file}"] = { :time => "#{time}", :rc => "#{rc}", :host => "#{host}", :ip => "#{ip}" }
Every time you call @records = {}
the instance variable points to a new hash. Thus the initialization code in initialize
has no effect. Rather than replace the initialized hash with a new one, you should add new entry to the existing hash, using the []=
instance method of Hash
.
BTW, you can use variable
to refer to the string rather than creating a new one using string interpolation "#{variable}"
.
@records[file] = { :time => time, :rc => rc, :host => host, :ip => ip }
If you want the UPDATE behavior for both the first and the second layers of the hash, you can take a look at the Hash#update
method.
@records[file].update({ :time => time, :rc => rc, :host => host, :ip => ip })
Add a new pair to an existing Hash
How about:
sizes[@thumb.to_sym] = ["100x100"]
# or
sizes.merge!(@thumb.to_sym => ["100x100"])
Related Topics
Rails: How to Pass Custom Params to a Controller Method
Cannot Install Ruby 1.9.3 on a Clean Lion Install
Error Occurs When Trying to Install Homebrew on a MAC for Ruby on Rails
Rails "Template Is Missing" Error
Rails Form_For Never Invokes the Create Controller Action to Use Redirect_To
Tilt (Kramdown) Preventing Erb Processing When Rendering Markdown
Ruby, Value Bucketing, Beautify Code
Ruby: Sorting 2 Arrays Using Values from One of Them
Ruby: How to Remove Items from Array a If It's Not in Array B
How to Properly Create a Associated Record Just After the Associator Record Creation
Multiple Limit Condition in Mongodb
Is It a Bad Idea Do Divide the Models into Directories
PDF Generation Hangs Using PDFkit and Wkhtmotopdf
Differencebetween 'Raise "Foo"' and 'Raise Exception.New("Foo")'