Skip to content

Instantly share code, notes, and snippets.

@newfront
Created February 11, 2011 19:45
Show Gist options
  • Save newfront/822880 to your computer and use it in GitHub Desktop.
Save newfront/822880 to your computer and use it in GitHub Desktop.
Notes to help remember the interesting tidbits
(hash).store
method adds a new value into the Hash
----------------
h = {}
h.store(:a,5)
h => {:a => 5}
----------------
(hash).merge, (hash).merge!, (hash).update #(hash).update is same as (hash).merge
Merges one hash with another
-----------------
h = {:a=>5,:b=>4,:c=>9}
j = {:d=>10,:e=>9}
h.merge(j)
=> {:a=>5, :b=>4, :c=>9, :d=>10, :e=>9}
------------------
(hash).delete_if
-------------------
(using h from above)
h.delete_if {|k,v| v > 8}
=> {:a=>5, :b=>4}
--------------------
(hash).delete (key)
--------------------
h.delete :b if h.include? :b
=> {:a=>5}
(hash).each_key, (hash).each_value, (hash).each_pair
---------------------
h = {:a=>5, :b=>4, :c=>9, :d=>10, :e=>9}
h.each_key{|k| puts "key: #{k}"}
output:
key: a
key: b
key: c
key: d
key: e
h.each_value{|v| puts "value: #{v}"}
output:
value: 5
value: 4
value: 9
value: 10
value: 9
h.each_pair{|k,v| puts "key: #{k}, value: #{v}"}
output:
key: a, value: 5
key: b, value: 4
key: c, value: 9
key: d, value: 10
key: e, value: 9
*note: each_pair is the same as each
(hash).fetch(key)
-----------------
h.fetch(:a)
=> 5
Error is key not found, or local variable or method undefined if no key exists
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment