Created
February 19, 2009 12:56
-
-
Save fdutey/66911 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h = { "a" => 1, "b" => 2, "c" => 3 } | |
#La syntaxe de Ruby permet ceci | |
a, b = ["a", "b"] | |
a #=> "a" | |
b #=> "b" | |
#N'avons nous pas dit qu'un Hash était un tableau de tableaux? | |
h.each{ |obj| puts obj.class } #=> Array \n Array | |
#Si notre bloc prend 2 paramètres, alors le tour est joué. | |
#Ruby va attribuer les 2 valeurs contenues dans la paire à nos deux variables. | |
h.each{ |key, value| puts "#{key} => #{value}" } #=> a => 1 \n b => 2 \n c => 3 | |
#Pour inject, les choses se corsent | |
h.inject(""){ |memo, key, value| memo << "#{key} => #{value}" } #=> "a1 => b2 => c3 =>" | |
#Aie, ou est l'erreur? | |
["a", 1].to_s #=> "a1" | |
#donc si je récapitule: memo => string, key => Array, value => nil. | |
#Mais on a dit pourtant qu'il suffisait de remplacer la variable "item" par 2 variables pour résoudre le probleme? | |
#Pas vraiment. Inject envoie la structure suivante au bloc | |
#[memo, [key, value]]. | |
a, b, c = ["", ["a", 1]] | |
a #=> "" | |
b #=> ["a", 1] | |
c #=> nil | |
#Il faut "expliquer" à ruby qu'il doit considérer b et c sont 1 seule variable qui correspond à la 2eme case du tableau des arguments (soit ["a", 1]) | |
a, (b, c) = ["", ["a", 1]] | |
a #=> "" | |
b #=> "a" | |
c #=> 1 | |
#Du coup | |
h.inject([]){ |memo, (key, value)| memo << "#{key} => #{value}" }.join(', ') #=> "a => 1, b => 2, c => 3" | |
#Et voila :> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment