Link copiato negli appunti
Difficile scrivere più di qualche riga di codice senza incontrare un Hash. Ecco alcune valide estensioni, cominciando da quelle per fondere o confrontare due Hash.
require '../helper'
# deep_merge e deep_merge! eseguono il merge
# ricorsivo di due Hash.
hash1 = {:foo => {:one => 1, :two => 2}}
hash2 = {:foo => {:three => 3}, :bar => 'baz'}
hash1.deep_merge(hash2).inspect
# => {:bar=>"baz", :foo=>{:three=>3, :one=>1, :two=>2}}
# reverse_merge esegue il merge di due hash
# dando precedenza alle chiavi dell'hash originale.
# estremamente utile per fornire dei valori di default
# ai parametri di un metodo.
def method_name(options = {})
options = options.reverse_merge! :foo => 'bar'
puts options.inspect
end
method_name :bar => 'baz'
# => {:bar=>"baz", :foo=>"bar"}
method_name :foo => 'foo', :bar => 'baz'
# => {:bar=>"baz", :foo=>"foo"}
Infine, altri metodi per escludere determinati elementi o modificare il tipo di chiave per gli elementi da stringa a simbolo o viceversa.
require '../helper'
# except e except! restituiscono/modificano un Hash
# escludendo le chiavi indicate.
hash = { :foo => 1, :bar => 2, :baz => 3 }
hash.except(:foo, :bar).inspect
# => {:baz => 3}
hash.except!(:foo)
hash.inspect
# => {:bar => 2, :baz => 3}
# i metodi stringify_keys, symbolize_keys
# e rispettivi stringify_keys!, symbolize_keys!
# convertono il tipo di oggetto usato
# come chiave dell'Hash.
hash = { :foo => 1, :bar => 2, :baz => 3 }
hash.stringify_keys.inspect
# => {"baz"=>3, "foo"=>1, "bar"=>2}
hash = { "baz" => 3, "foo" => 1, "bar" => 2 }
hash.symbolize_keys.inspect
# => {:foo=>1, :bar=>2, :baz=>3}
Range
I Range sono un tipo di dati meno conosciuto ma non per questo di minore importanza in Ruby. ActiveSupport ha pensato anche a loro.
require '../helper' # Restituisce un array se #step # è chiamato senza blocco # Utile per generare rapidamente un array array = (1..10).step # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # include? supporta un Range come parametro (1..5).include?(1..5) # => true (1..5).include?(2..3) # => true # overlaps? compara due Range e # restituisce true in caso di sovrapposizioni (1..5).overlaps?(4..6) # => true (1..5).overlaps?(7..9) # => false
Se vuoi aggiornamenti su Development inserisci la tua email nel box qui sotto: