summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--es-es/jquery-es.html.markdown4
-rw-r--r--fr-fr/binary-search-fr.html.markdown67
-rw-r--r--fr-fr/dynamic-programming-fr.html.markdown55
-rw-r--r--fr-fr/jquery-fr.html.markdown142
-rw-r--r--java.html.markdown12
-rw-r--r--jquery.html.markdown8
-rw-r--r--perl6.html.markdown169
-rw-r--r--pt-br/ruby-pt.html.markdown58
8 files changed, 456 insertions, 59 deletions
diff --git a/es-es/jquery-es.html.markdown b/es-es/jquery-es.html.markdown
index d35e6f17..27ad48bb 100644
--- a/es-es/jquery-es.html.markdown
+++ b/es-es/jquery-es.html.markdown
@@ -79,7 +79,7 @@ $('#btn').on(
);
// Puede mover y ocultar elementos con algunos métodos de efecto
-$('.table').hide(); # Oculta el(los) elemento(s)
+$('.table').hide(); // Oculta el(los) elemento(s)
// Nota: llamar a una función en estos métodos aún oculta el elemento
$('.table').hide(function(){
@@ -134,7 +134,7 @@ $('p').height(); // Obtiene sólo la altura de la primera etiqueta 'p'
// Puedes utilizar 'each' para recorrer todos los elementos
var heights = [];
$('p').each(function() {
- heights.push($(this.height)); // Añade todas las alturas "p" de la etiqueta a la matriz
+ heights.push($(this).height()); // Añade todas las alturas "p" de la etiqueta a la matriz
});
diff --git a/fr-fr/binary-search-fr.html.markdown b/fr-fr/binary-search-fr.html.markdown
new file mode 100644
index 00000000..4c34da0f
--- /dev/null
+++ b/fr-fr/binary-search-fr.html.markdown
@@ -0,0 +1,67 @@
+---
+category: Algorithms & Data Structures
+name: Binary Search
+contributors:
+ - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+# Recherche Binaire
+
+## Pourquoi la Recherche Binaire ?
+
+La recherche est un des principaux problèmes dans le domaine de l'informatique. De nos jours, il y a plus de 1 milliard de recherches par année, et nous avons besoin d'algorithmes pour faire cela rapidement. La recherche binaire est un des algorithmes les plus fondamentaux en informatique. Pour pouvoir l'explorer en détail, nous allons d'abord établir une base théorique, puis nous allons utiliser cette base pour implémenter l'algorithme en soi.
+
+## Introduction
+
+Une façon simple d'implémenter la recherche est de faire une recherche linéaire. Cependant, cette approche prend beaucoup de temps, et ce temps augmente linéairement avec la quantité de données. Par exemple, partons du premier élément d'un tableau t[], et un par un, comparons x avec chaque élément de t[]. Si x est égal à un élément, nous retournons l'index, si x n'égale aucun élément, nous retournons -1.
+
+```
+Recherche Linéaire: O (n) Temps Linéaire
+
+Recherche Binaire: O ( log(n) ) Temps Logarithmique
+
+```
+```
+def search(arr, x):
+
+ for i in range(len(arr)):
+
+ if arr[i] == x:
+ return i
+
+ return -1
+
+```
+## L'Algorithme de Recherche Binaire
+
+Le prérequis fondamental de la recherche binaire est que les éléments soient triés.
+
+### Algo
+
+```
+L'idée derrière la recherche binaire est d'utiliser le fait que le tableau est trié afin de réduire la complexité à O(Log(n)). Nous pouvons ignorer la moitié des éléments après la première comparaison.
+1) Comparons x avec l'élément du milieu.
+2) Si x est égal à cet élément, nous retournons l'index du milieu.
+3) Sinon, si x est plus grand que l'élément du milieu, alors x peut seulement être dans la dernière moitié du tableau. Donc, nous recommençons la procédure avec cette dernière moitié.
+4) Sinon (x est plus petit), nous recommençons la procédure avec la première moitié du tableau.
+Ensuite nous avons une implémentation récursive de la recherche binaire.
+
+```
+
+### Note de la fin
+
+Partie en construction.
+
+## Livre
+
+* [CLRS EN](https://mitpress.mit.edu/books/introduction-algorithms)
+* [Algorithmes EN](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
+* [Design d'Algorithmes EN](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
+
+## Ressources en ligne
+
+* [GeeksforGeeks EN](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
+* [Topcoder Tutorial EN](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown
new file mode 100644
index 00000000..24e8c95f
--- /dev/null
+++ b/fr-fr/dynamic-programming-fr.html.markdown
@@ -0,0 +1,55 @@
+---
+category: Algorithms & Data Structures
+name: Dynamic Programming
+contributors:
+ - ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+
+# Programmation dynamique
+
+## Introduction
+
+La programmation dynamique est une technique très efficace pour résoudre une certaine classe de problèmes, comme nous allons le voir. L'idée est très simple, si nous avons résolu un problème avec une certaine entrée, alors nous sauvons le résultat pour pouvoir y accéder plus tard, pour éviter d'avoir à le calculer à nouveau.
+
+## Moyens de résoudre ces problèmes
+
+1.) *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation.
+
+2.) *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique.
+
+## Exemple de Programmation Dynamique
+
+Le problème de la plus grande sous-chaîne croissante est de trouver la plus grande sous-chaîne croissante dans une chaîne. Soit la chaîne `S = {a1, a2, a3, a4, ............., an-1, an}`, nous avons à trouver la plus grande chaîne telle que pour tout `j` et `i`, `j<i` dans la chaîne `aj<ai`.
+Premièrement, nous avons à trouver la valeur de la plus grande sous-chaîne (LSi) à chaque index `i`, avec le dernier élément de la sous-chaîne étant ai. Alors, la plus grande sous-chaîne sera le plus gros LSi. Pour commencer, LSi est égal à 1, car ai est le seul élément de la chaîne (le dernier). Ensuite, pour chaque `j` tel que `j<i` et `aj<ai`, nous trouvons le plus grand LSj et ajoutons le à LSi. L'algorithme fonctionne en temps *O(n2)*.
+
+Pseudo-code pour trouver la longueur de la plus grande sous-chaîne croissante :
+La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme plus_grande_chaîne_jusqu'à_maintenant et son index, nous pourrions sauver beaucoup de temps.
+
+Le même concept peut être appliqué pour trouver le chemin le plus long dans un graphe acyclique orienté.
+
+```python
+ for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+ for i=0 to n-1
+ if (largest < LS[i])
+```
+
+### Problèmes classiques de programmation dynamique
+
+L'algorithme de Floyd Warshall(EN)) - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
+
+Problème du sac à dos(EN) - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+
+
+Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
+
+## Online Resources
+
+* [codechef EN](https://www.codechef.com/wiki/tutorial-dynamic-programming)
diff --git a/fr-fr/jquery-fr.html.markdown b/fr-fr/jquery-fr.html.markdown
new file mode 100644
index 00000000..1842e02b
--- /dev/null
+++ b/fr-fr/jquery-fr.html.markdown
@@ -0,0 +1,142 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Sawyer Charles", "https://github.com/xssc"]
+translators:
+ - ["Sylvain Vaure", "https://github.com/Gnomino"]
+filename: jquery-fr.js
+lang: fr-fr
+---
+
+jQuery est une bibliothèque JavaScript dont le but est de permettre de "faire plus en écrivant moins" (do more, write less). Elle facilite l'écriture de nombreuses fonctions, notamment au niveau d'AJAX, de la gestion d'événements, ou encore de la manipulation de documents.
+C'est pourquoi aujourd'hui, jQuery est utilisée par de nombreuses grandes entreprises et par des développeurs du monde entier.
+
+Étant donné que jQuery est une bibliothèque JavaScript, vous devriez d'abord [apprendre le JavaScript](https://learnxinyminutes.com/docs/fr-fr/javascript-fr/)
+```js
+
+
+///////////////////////////////////
+// 1. Les sélecteurs
+
+// On utilise les sélecteurs de jQuery pour sélectionner des éléments
+var page = $(window); // Sélectionne tout le viewport
+
+// On peut aussi utiliser des sélecteurs CSS
+var paragraph = $('p'); // Sélectionne tous les éléments paragraphes
+var table1 = $('#table1'); // Sélectionne l'élément qui a l'id 'table1'
+var squares = $('.square'); // Sélectionne tous les éléments avec la classe 'square'
+var square_p = $('p.square') // Sélectionne tous les paragraphes avec la classe 'square'
+
+
+///////////////////////////////////
+// 2. Événements et effets
+// jQuery gère très bien ce qui se passe lorsqu'un événement est déclenché
+// L'événement 'ready' est très souvent utilisé sur le document
+// On utilise la méthode 'ready' pour attendre que l'élément ait fini de se charger
+$(document).ready(function(){
+ // Ce code ne s'exécutera pas avant que le document soit chargé (prêt)
+});
+// On peut aussi utiliser des fonctions définies
+function onAction() {
+ // Ceci est exécuté quand l'événement est déclenché
+}
+$('#btn').click(onAction); // Appelle onAction à chaque clic
+
+function onAction() {
+ // Ceci est exécuté quand un évènement est déclenché
+}
+
+// D'autres évènements communs :
+$('#btn').dblclick(onAction); // Double clic
+$('#btn').hover(onAction); // Survol de la souris
+$('#btn').focus(onAction); // Gain du focus
+$('#btn').blur(onAction); // Perte du focus
+$('#btn').submit(onAction); // Envoi (d'un formulaire)
+$('#btn').select(onAction); // Quand un élement est sélectionné
+$('#btn').keydown(onAction); // Quand une touche est enfoncée
+$('#btn').keyup(onAction); // Quand une touche est relâchée
+$('#btn').keypress(onAction); // Quand on appuie sur un touche
+$('#btn').mousemove(onAction); // Quand la souris se déplace
+$('#btn').mouseenter(onAction); // La souris entre dans l'élément
+$('#btn').mouseleave(onAction); // La souris sort de l'élément
+
+// On peut aussi utiliser des fonctions lambdas
+$('#btn').hover(function(){
+ // exécuté lors d'un survol de la souris
+});
+
+// Il est possible de déclencher l'événement sans le gérer
+// simplement en ne passant aucun paramètre à la méthode
+$('#btn').dblclick(); // Simule un double clic sur l'élément
+
+// On peut gérer plusieurs événements en utilisant le sélecteur une seule fois
+$('#btn').on(
+ {dblclick: myFunction1} // Déclenché à chaque double clic
+ {blur: myFunction1} // Déclenché quand l'élément perd le focus
+);
+
+// On peut déplacer et cacher des éléments grâce à des fonctions d'effets
+$('.table').hide(); // Cache le(s) élément(s)
+
+// Note: même avec un appel à une fonction dans ces méthodes
+// cache quand même l'élément
+$('.table').hide(function(){
+ // L'élément est caché, puis la fonction est exécutée
+});
+
+// On peut stocker des sélecteurs dans des variables
+var tables = $('.table');
+
+// Des méthodes basique de manipulation de document :
+tables.hide(); // Cache un(des) élément(s)
+tables.show(); // Montre (dé-cache) un(des) élément(s)
+tables.toggle(); // Change le statut le statut caché/montré
+tables.fadeOut(); // Fait disparaître l'élément
+tables.fadeIn(); // Fait apparaître l'élément
+tables.fadeToggle(); // Fait apparaître ou disparaître
+tables.fadeTo(0.5); // Fondu jusqu'à une certaine opacité (entre 0 et 1)
+tables.slideUp(); // Cache l'élément avec un effet de glissement vers le haut
+tables.slideDown(); // Fait apparaître l'élément avec un glissement vers le bas
+tables.slideToggle(); // Cache/Montre l'élément avec un effet de glissement
+
+// Les méthodes ci-dessus prennent en arguments
+// une vitesse (millisecondes) et une function callback
+tables.hide(1000, myFunction); // Animation d'une seconde, puis appel à la fonction
+
+// fadeTo doit avoir une opacité entre 0 et 1 comme deuxième argument
+tables.fadeTo(2000, 0.1, myFunction); // 2 sec. fade to 0.1 opacity then function
+
+// La méthode animate permet des animations légèrement plus poussées
+tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
+// La méthode prend un objet de css et de valeurs finales,
+// des paramètres d'options facultatifs pour régler l'animation,
+// et bien sûr la fonction callback
+
+///////////////////////////////////
+// 3. Manipulation
+
+// Ces méthodes sont similaires aux effets mais permettent d'aller plus loin
+$('div').addClass('taming-slim-20'); // Ajoute la classe taming-slim-20 aux div
+
+// Méthodes ordinaires de manipulation
+$('p').append('Hello world'); // Ajoute à la fin de l'élément
+$('p').attr('class'); // Renvoie la valeur de l'attribut
+$('p').attr('class', 'content'); // Change la valeur de l'attribut
+$('p').hasClass('taming-slim-20'); // Renvoie vrai si l'élément est de la classe
+$('p').height(); // Renvoie la hauteur de l'élément ou la change
+
+
+// Pour beaucoup de méthodes de manipulation, récupérer des informations
+// d'un élément renverra SEULEMENT ceelles du premier
+$('p').height(); // Renvoie SEULEMENT la hauteur du premier élément 'p'
+
+// On peut utiliser 'each' pour parcourir tous les éléments
+var heights = [];
+$('p').each(function() {
+ heights.push($(this).height()); // Ajoute la hauteur de tous les éléments 'p' à la liste
+});
+
+
+``
+
diff --git a/java.html.markdown b/java.html.markdown
index 6753b358..4fdd06cc 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -95,6 +95,12 @@ public class LearnJava {
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
+
+ // If you would like to interpret a byte as an unsigned integer
+ // then this simple operation can help
+ int unsignedIntLessThan256 = 0xff & fooByte;
+ // this contrasts a cast which can be negative.
+ int signedInt = (int) fooByte;
// Short - 16-bit signed two's complement integer
// (-32,768 <= short <= 32,767)
@@ -102,7 +108,7 @@ public class LearnJava {
// Integer - 32-bit signed two's complement integer
// (-2,147,483,648 <= int <= 2,147,483,647)
- int fooInt = 1;
+ int bazInt = 1;
// Long - 64-bit signed two's complement integer
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
@@ -110,7 +116,9 @@ public class LearnJava {
// L is used to denote that this variable value is of type Long;
// anything without is treated as integer by default.
- // Note: Java has no unsigned types.
+ // Note: byte, short, int and long are signed. They can have positive and negative values.
+ // There are no unsigned variants.
+ // char, however, is 16-bit unsigned.
// Float - Single-precision 32-bit IEEE 754 Floating Point
// 2^-149 <= float <= (2-2^-23) * 2^127
diff --git a/jquery.html.markdown b/jquery.html.markdown
index ffac93f8..d498733d 100644
--- a/jquery.html.markdown
+++ b/jquery.html.markdown
@@ -66,7 +66,7 @@ $('#btn').on(
);
// You can move and hide elements with some effect methods
-$('.table').hide(); # Hides the element(s)
+$('.table').hide(); // Hides the element(s)
// Note: calling a function in these methods will still hide the element
$('.table').hide(function(){
@@ -104,13 +104,13 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
// 3. Manipulation
// These are similar to effects but can do more
-$('div').addClass('div'); // Adds class div to all div taming-slim-20
+$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div
// Common manipulation methods
$('p').append('Hello world'); // Adds to end of element
$('p').attr('class'); // Gets attribute
$('p').attr('class', 'content'); // Sets attribute
-$('p').hasClass('div'); // Returns true if it has the class
+$('p').hasClass('taming-slim-20'); // Returns true if it has the class
$('p').height(); // Gets height of element or sets height
@@ -121,7 +121,7 @@ $('p').height(); // Gets only the first 'p' tag's height
// You can use each to loop through all the elements
var heights = [];
$('p').each(function() {
- heights.push($(this.height)); // Adds all 'p' tag heights to array
+ heights.push($(this).height()); // Adds all 'p' tag heights to array
});
diff --git a/perl6.html.markdown b/perl6.html.markdown
index d31955f0..8fcf9a02 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,7 +1,7 @@
---
category: language
language: perl6
-filename: learnperl6.pl
+filename: learnperl6.p6
contributors:
- ["vendethiel", "http://github.com/vendethiel"]
---
@@ -798,19 +798,47 @@ class Item does PrintableVal {
### Exceptions
# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-# You can access the last exception with the special variable `$!`
-# (use `$_` in a `CATCH` block) Note: This has no relation to $!variables.
+# In Perl6 exceptions are automatically 'thrown'
+open 'foo'; #> Failed to open file foo: no such file or directory
+# It will also print out what line the error was thrown at and other error info
# You can throw an exception using `die`:
-open 'foo' or die 'Error!'; #=> Error!
+die 'Error!'; #=> Error!
# Or more explicitly:
die X::AdHoc.new(payload => 'Error!');
+# In Perl 6, `orelse` is similar to the `or` operator, except it only matches
+# undefined variables instead of anything evaluating as false.
+# Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
+# and other types that have not been initialized to any value yet.
+# You can check if something is defined or not using the defined method:
+my $uninitialized;
+say $uninitiazilzed.defined; #> False
+# When using `orelse` it will disarm the exception and alias $_ to that failure
+# This will avoid it being automatically handled and printing lots of scary
+# error messages to the screen.
+# We can use the exception method on $_ to access the exception
+open 'foo' orelse say "Something happened {.exception}";
+# This also works:
+open 'foo' orelse say "Something happened $_"; #> Something happened
+ #> Failed to open file foo: no such file or directory
+# Both of those above work but in case we get an object from the left side that
+# is not a failure we will probably get a warning. We see below how we can use
+# `try` and `CATCH` to be more specific with the exceptions we catch.
+
## Using `try` and `CATCH`
# By using `try` and `CATCH` you can contain and handle exceptions without
-# disrupting the rest of the program.
+# disrupting the rest of the program. `try` will set the last exception to
+# the special variable `$!` Note: This has no relation to $!variables.
+try open 'foo';
+say "Well, I tried! $!" if defined $!; #> Well, I tried! Failed to open file
+ #foo: no such file or directory
+# Now, what if we want more control over handling the exception?
# Unlike many other languages, in Perl 6, you put the `CATCH` block *within*
-# the block to `try`. By default, a `try` has a `CATCH` block that catches
+# the block to `try`. Similar to how $_ was set when we 'disarmed' the
+# exception with orelse, we also use $_ in the CATCH block.
+# Note: ($! is only set *after* the `try` block)
+# By default, a `try` has a `CATCH` block that catches
# any exception (`CATCH { default {} }`).
try { my $a = (0 %% 0); CATCH { say "Something happened: $_" } }
@@ -877,7 +905,7 @@ module Hello::World { # Bracketed form
unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
-}
+} # You will learn more about grammars in the regex section
# As said before, any part of the six model is also a package.
# Since `JSON::Tiny` uses (its own) `JSON::Tiny::Actions` class, you can use it:
@@ -889,25 +917,33 @@ my $actions = JSON::Tiny::Actions.new;
# In Perl 6, you get different behaviors based on how you declare a variable.
# You've already seen `my` and `has`, we'll now explore the others.
-## * `our` (happens at `INIT` time -- see "Phasers" below)
+## * `our` declarations happen at `INIT` time -- (see "Phasers" below)
# It's like `my`, but it also creates a package variable.
# (All packagish things (`class`, `role`, etc) are `our` by default)
-module Foo::Bar {
- our $n = 1; # note: you can't put a type constraint on an `our` variable
- our sub inc {
+module Var::Increment {
+ our $our-var = 1; # Note: you can't put a type constraint like Int on an
+ my $my-var = 22; # `our` variable.
+ our sub Inc {
+
our sub available { # If you try to make inner `sub`s `our`...
# Better know what you're doing (Don't !).
- say "Don't do that. Seriously. You'd get burned.";
+ say "Don't do that. Seriously. You'll get burned.";
}
+
my sub unavailable { # `my sub` is the default
- say "Can't access me from outside, I'm my !";
+ say "Can't access me from outside, I'm 'my'!";
}
- say ++$n; # increment the package variable and output its value
+ say ++$our-var; # Increment the package variable and output its value
}
+
}
-say $Foo::Bar::n; #=> 1
-Foo::Bar::inc; #=> 2
-Foo::Bar::inc; #=> 3
+say $Var::Increment::our-var; #=> 1 This works
+say $Var::Increment::my-var; #=> (Any) This will not work.
+
+Var::Increment::Inc; #=> 2
+Var::Increment::Inc; #=> 3 # Notice how the value of $our-var was
+ # retained.
+Var::Increment::unavailable; #> Could not find symbol '&unavailable'
## * `constant` (happens at `BEGIN` time)
# You can use the `constant` keyword to declare a compile-time variable/symbol:
@@ -944,10 +980,11 @@ for ^5 -> $a {
### Phasers
# Phasers in Perl 6 are blocks that happen at determined points of time in your
-# program. When the program is compiled, when a for loop runs, when you leave a
-# block, when an exception gets thrown ... (`CATCH` is actually a phaser !)
+# program. They are called phasers because they mark a change in the phase
+# of a program. For example, when the program is compiled, a for loop runs,
+# you leave a block, or an exception gets thrown. (`CATCH` is actually a phaser !)
# Some of them can be used for their return values, some of them can't
-# (those that can have a "[*]" in the beginning of their explanation text).
+# (those that can have a "[*]" in the beginning of their explanation text).
# Let's have a look !
## * Compile-time phasers
@@ -1046,15 +1083,25 @@ constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything
# versus:
constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2
-# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
-# Not yet implemented !!
+### Iterables
+# Iterables are objects that can be iterated similar to the `for` construct
+# `flat`, flattens iterables:
+say (1, 10, (20, 10) ); #> (1 10 (20 10)) Notice how grouping is maintained
+say (1, 10, (20, 10) ).flat; #> (1 10 20 10) Now the iterable is flat
+# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
+my @lazy-array = (1..100).lazy;
+say @lazy-array.is-lazy; #> True # Check for lazyness with the `is-lazy` method.
+say @lazy-array; #> [...] List has not been iterated on!
+my @lazy-array { .print }; # This works and will only do as much work as is
+# needed.
+[//]: # ( TODO explain that gather/take and map are all lazy)
# - `sink` - An `eager` that discards the results (forces sink context)
constant nilthingie = sink for ^3 { .say } #=> 0 1 2
say nilthingie.perl; #=> Nil
-# - `quietly` - Supresses warnings
-# Not yet implemented !
+# - `quietly` blocks will suppress warnings:
+quietly { warn 'This is a warning!' }; #=> No output
# - `contend` - Attempts side effects under STM
# Not yet implemented !
@@ -1064,7 +1111,7 @@ say nilthingie.perl; #=> Nil
## Everybody loves operators ! Let's get more of them
# The precedence list can be found here:
-# http://perlcabal.org/syn/S03.html#Operator_precedence
+# https://docs.perl6.org/language/operators#Operator_Precedence
# But first, we need a little explanation about associativity:
# * Binary operators:
@@ -1258,7 +1305,7 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
# (grammars are actually classes)
# - Earliest declaration wins
say so 'a' ~~ /a/; #=> True
-say so 'a' ~~ / a /; # More readable with some spaces!
+say so 'a' ~~ / a /; #=> True # More readable with some spaces!
# In all our examples, we're going to use the smart-matching operator against
# a regexp. We're converting the result using `so`, but in fact, it's
@@ -1274,50 +1321,63 @@ say so 'a' ~~ / a /; # More readable with some spaces!
# In Perl 6, you can have any alphanumeric as a literal,
# everything else has to be escaped, using a backslash or quotes.
-say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped
+say so 'a|b' ~~ / a '|' b /; # `True`. Wouldn't mean the same if `|` wasn't escaped
say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it.
# The whitespace in a regexp is actually not significant,
-# unless you use the `:s` (`:sigspace`, significant space) modifier.
-say so 'a b c' ~~ / a b c /; # `False`. Space is not significant here
-say so 'a b c' ~~ /:s a b c /; # `True`. We added the modifier `:s` here.
-
+# unless you use the `:s` (`:sigspace`, significant space) adverb.
+say so 'a b c' ~~ / a b c /; #> `False`. Space is not significant here
+say so 'a b c' ~~ /:s a b c /; #> `True`. We added the modifier `:s` here.
+# If we use only one space between strings in a regex, Perl 6 will warn us:
+say so 'a b c' ~~ / a b c /; #> 'False' #> Space is not significant here; please
+# use quotes or :s (:sigspace) modifier (or, to suppress this warning, omit the
+# space, or otherwise change the spacing)
+# To fix this and make the spaces less ambiguous, either use at least two
+# spaces between strings or use the `:s` adverb.
+
+# As we saw before, we can embed the `:s` inside the slash delimiters, but we can
+# also put it outside of them if we specify `m` for 'match':
+say so 'a b c' ~~ m:s/a b c/; #> `True`
+# By using `m` to specify 'match' we can also use delimiters other than slashes:
+say so 'abc' ~~ m{a b c}; #> `True`
+# Use the :i adverb to specify case insensitivity:
+say so 'ABC' ~~ m:i{a b c}; #> `True`
# It is, however, important as for how modifiers (that you're gonna see just below)
# are applied ...
## Quantifying - `?`, `+`, `*` and `**`.
# - `?` - 0 or 1
-so 'ac' ~~ / a b c /; # `False`
-so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times.
-so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time.
+so 'ac' ~~ / a b c /; # `False`
+so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times.
+so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time.
# ... As you read just before, whitespace is important because it determines
# which part of the regexp is the target of the modifier:
-so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional
-so 'def' ~~ / ab?c /; # `False`. Whitespace is not significant
+so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional
+so 'def' ~~ / a b? c /; # `False`. Whitespace is not significant
so 'def' ~~ / 'abc'? /; # `True`. The whole "abc" group is optional.
# Here (and below) the quantifier applies only to the `b`
# - `+` - 1 or more
-so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching
-so 'abc' ~~ / a b+ c /; # `True`; one is enough
-so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
+so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching
+so 'abc' ~~ / a b+ c /; # `True`; one is enough
+so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
# - `*` - 0 or more
-so 'ac' ~~ / a b* c /; # `True`, they're all optional.
-so 'abc' ~~ / a b* c /; # `True`
-so 'abbbbc' ~~ / a b* c /; # `True`
-so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
+so 'ac' ~~ / a b* c /; # `True`, they're all optional.
+so 'abc' ~~ / a b* c /; # `True`
+so 'abbbbc' ~~ / a b* c /; # `True`
+so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
# - `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand
# why exponentation is used for quantity.
-so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time)
-so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times)
-so 'abbbc' ~~ / a b ** 1..3 c /; # `True`
-so 'abbbbbbc' ~~ / a b ** 1..3 c /; # `False` (too much)
-so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)
+so 'abc' ~~ / a b**1 c /; # `True` (exactly one time)
+so 'abc' ~~ / a b**1..3 c /; # `True` (one to three times)
+so 'abbbc' ~~ / a b**1..3 c /; # `True`
+so 'abbbbbbc' ~~ / a b**1..3 c /; # `False` (too much)
+so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (infinite ranges are okay)
# - `<[]>` - Character classes
# Character classes are the equivalent of PCRE's `[]` classes, but
@@ -1561,7 +1621,18 @@ for <a b c> {
If you want to go further, you can:
- - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such.
+ - Read the [Perl 6 Docs](https://docs.perl6.org/). This is a great
+ resource on Perl6. If you are looking for something, use the search bar.
+ This will give you a dropdown menu of all the pages referencing your search
+ term (Much better than using Google to find Perl 6 documents!)
+ - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This
+ is a great source of Perl 6 snippets and explainations. If the docs don't
+ describe something well enough, you may find more detailed information here.
+ This information may be a bit older but there are many great examples and
+ explainations. Posts stopped at the end of 2015 when the language was declared
+ stable and Perl 6.c was released.
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
+
+ [//]: # ( vim: set filetype=perl softtabstop=2 shiftwidth=2 expandtab cc=80 : )
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index eeb51bec..1078f6c5 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"]
translators:
- ["Katyanna Moura", "https://twitter.com/amelie_kn"]
+ - ["Alan Peterson Carvalho Silva", "https://twitter.com/DemonKart"]
---
```ruby
@@ -382,12 +383,65 @@ end
Humano.bar # 0
Doutor.bar # nil
+---
+
+module ModuloDeExemplo
+ def foo
+ 'foo'
+ end
+end
+
+# Incluir (include) módulos conecta seus métodos às instâncias da classe
+# Herdar (extend) módulos conecta seus métodos à classe em si
+
+class Pessoa
+ include ExemploDeModulo
+end
+
+class Livro
+ extend ExemploDeModulo
+end
+
+Pessoa.foo # => NoMethodError: undefined method `foo' for Pessoa:Class
+Pessoa.new.foo # => 'foo'
+Livro.foo # => 'foo'
+Livro.new.foo # => NoMethodError: undefined method `foo'
+
+# Callbacks são executados ao incluir e herdar um módulo
+
+module ExemploDeConceito
+ def self.included(base)
+ base.extend(MetodosDeClasse)
+ base.send(:include, MetodosDeInstancia)
+ end
+
+ module MetodosDeClasse
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodosDeInstancia
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Algo
+ include ExemploDeConceito
+end
+
+Algo.bar # => 'bar'
+Algo.qux # => NoMethodError: undefined method `qux'
+Algo.new.bar # => NoMethodError: undefined method `bar'
+Algo.new.qux # => 'qux'
```
-## Mais sobre Ruby
+## Recursos adicionais
-- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/)
- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem.
+- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/)
- [Ruby a partir de outras linguagens](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide*