Hash

1.9 vs 1.8 syntax

{:a => 1, :b => 2, :c => 3}  #1.9 syntax
ruby 1.8 1.9+
{ :a => 1, :b => 2, :c => 3 } OK OK
{ a: 1, b: 2, c: 3 } x OK

Set default value for unexisting keys of a hash

i_am_a_hash = Hash.new
i_am_a_hash.default = 0
i_am_a_hash[1]
#=> 0

slice

only return a new hash with the given keys

a_hash = {:a=>1, :b=>2, :c=>3}
a_hash.slice(:a, :c)
#=> {:a=>1, :c=>3}


key_set = [:a, :b]
a_hash.slice(*key_set)
#=> {:a=>1, :b=>2 }
  • slice!: replaces the hash with the given keys, same as extract!(in Rails 4.0+, in 3.2 was different behavior, refer to the notes on apidock)

except

return a new hash without the given keys

a_hash = {:a=>1, :b=>2, :c=>3}
a_hash.except(:a, :c)
#=> {:b=>2}
  • except!: replaces the hash without the given keys

check if a hash contains a set of keys

a_hash = {a:1, b:2, c:3, d:4}

all?: check all keys exist

[:a, :b, :c, :d].all? {|k| a_hash.key?(k)}
#=> true
[:a, :b, :c, :e].all? {|k| a_hash.key?(k)}
#=> false

any?: check partial keys exist

[:a, :e, :f, :g].any? {|k| a_hash.key?(k)}
#=> true

Convert all string-keys to symbol

symbolize_keys!:modifies self

h = {"a"=>1, "b"=>"2", "c"=>"3"}
h.symbolize_keys!
puts h
# => {:a=>1, :b=>"2", :c=>"3"}

symbolize_keys:return a new all-keys-converted-to-symbols-hash

h2 = {"a"=>1, "b"=>"2", "c"=>"3"}
h3 = h2.symbolize_keys
puts h2
# => {"a"=>1, "b"=>"2", "c"=>"3"}
puts h3
# => {:a=>1, :b=>"2", :c=>"3"}

with_indifferent_access: implement\/return a hash which "key" and :key are considered to be the same

h4 = {"a"=>1, "b"=>"2", "c"=>"3"}
h5 = h4.with_indifferent_access # doesn't modifies self
puts h4["a"]
#=> 1
puts h4[:a]
#=> nil
puts h5["a"]
#=> 1
puts h5[:a]
#=> 1

#implement a hash "key" and ":key" are considered to be the same
hash = ActiveSupport::HashWithIndifferentAccess.new
# or
hash = {}.with_indifferent_access

Parsing XML

Hash.from_xml(xml_string)
# => #<Hash>
Hash.from_xml("<output errorCode=\"123\" error=\"error messages\" />"
#=> {"output"=> {"errorCode"=>"26", "error"=>"This amount can not be refunded"} }

Reference

results matching ""

    No results matching ""