Ruby class Hash interactive
→ Click to get an interactive sample (type in code)
! → Has also a bang method (modifies self)
Creating
# h = { a: 1, b: 2, c: 3 }
Methods
Creating a Hash
Setting Hash state
compare_by_identityh.compare_by_identity;h['a']… # {'a':1,'a':2} Documentation Playground
{"a" => 1, "a" => 2}Querying
Comparing
Fetching
Assigning
update (alias merge!)a={a:1,b:2}; b={a:7}; a.update(b) # {a:7,…} Documentation Playground
{a: 7, b: 2}replace (alias initialize_copy)a={a:1,b:2}; a.replace(a:7,c:8) # {a:7,c:8} Documentation Playground
{a: 7, c: 8}Deleting
! See non-bang methods for:
compact! select!→(alias filter) reject
Iterating
each (alias each_pair)h.each {|k,v| p "#{k}-#{v}"} # a-1;b-2;c-3 Documentation Playground
a-1|b-2|c-3|Converting
flattenh3={a:1,d:[:e]}.flatten(2) # [:a,1,:d,:e] Documentation Playground
[:a, {b: 1, c: 2}, :d, :e, :f, [:g]]Transforming Keys and Values
transform_keys!h.transform_keys{|k|k.to_s} # {'a'=>1,'b'=>…} Documentation Playground
{"a" => 1, "b" => 2, "c" => 3}transform_values!h.transform_values{|v|v+5} # {a:6,b:7,c:8} Documentation Playground
{a: 11, b: 12, c: 13}! See non-bang methods for:
transform_keys! transform_values!