summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--es-es/c-es.html.markdown2
-rw-r--r--es-es/elisp-es.html.markdown2
-rw-r--r--es-es/java-es.html.markdown2
-rw-r--r--es-es/python-es.html.markdown2
-rw-r--r--es-es/ruby-es.html.markdown377
-rw-r--r--pt-br/python-pt.html.markdown509
-rw-r--r--r.html.markdown20
-rw-r--r--ruby-ecosystem.html.markdown137
-rwxr-xr-xzh-cn/c-cn.html.markdown2
-rw-r--r--zh-cn/dart-cn.html.markdown3
-rwxr-xr-xzh-cn/elisp-cn.html.markdown2
-rwxr-xr-xzh-cn/git-cn.html.markdown1
-rwxr-xr-xzh-cn/haskell-cn.html.markdown4
-rwxr-xr-xzh-cn/java-cn.html.markdown2
-rwxr-xr-xzh-cn/javascript-cn.html.markdown1
-rwxr-xr-xzh-cn/php-cn.html.markdown2
-rwxr-xr-xzh-cn/python-cn.html.markdown2
-rw-r--r--zh-cn/ruby-cn.html.markdown3
-rw-r--r--zh-cn/scala-cn.html.markdown413
19 files changed, 1463 insertions, 23 deletions
diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown
index 0624f4be..b109f761 100644
--- a/es-es/c-es.html.markdown
+++ b/es-es/c-es.html.markdown
@@ -1,6 +1,6 @@
---
language: c
-filename: learnc.c
+filename: learnc-es.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
translators:
diff --git a/es-es/elisp-es.html.markdown b/es-es/elisp-es.html.markdown
index 431ea794..a6cd3934 100644
--- a/es-es/elisp-es.html.markdown
+++ b/es-es/elisp-es.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["Guillermo Vayá", "http://willyfrog.es"]
lang: es-es
-filename: learn-emacs-lisp.el
+filename: learn-emacs-lisp-es.el
---
```scheme
diff --git a/es-es/java-es.html.markdown b/es-es/java-es.html.markdown
index 90a43935..b34dca8d 100644
--- a/es-es/java-es.html.markdown
+++ b/es-es/java-es.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["Camilo Garrido", "http://www.twitter.com/hirohope"]
lang: es-es
-filename: LearnJava.java
+filename: LearnJava-es.java
---
Java es un lenguage de programación de propósito general, concurrente, basado en clases y
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 1ec8d7e4..f92f5cde 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["Camilo Garrido", "http://www.twitter.com/hirohope"]
lang: es-es
-filename: learnpython.py
+filename: learnpython-es.py
---
Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
new file mode 100644
index 00000000..66a5d0fe
--- /dev/null
+++ b/es-es/ruby-es.html.markdown
@@ -0,0 +1,377 @@
+---
+language: ruby
+filename: learnruby-es.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+translators:
+ - ["Camilo Garrido", "http://www.twitter.com/hirohope"]
+lang: es-es
+---
+
+```ruby
+# Esto es un comentario
+
+=begin
+Este es un comentario multilínea
+Nadie los usa.
+Tu tampoco deberías
+=end
+
+# Lo primero y principal: Todo es un objeto
+
+# Los números son objetos
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Un poco de aritmética básica
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# La aritmética es sólo azúcar sintáctico
+# para llamar un método de un objeto
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Los valores especiales son objetos
+nil # Nada que ver aqui
+true # Verdadero
+false # Falso
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Igualdad
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Desigualdad
+1 != 1 #=> false
+2 != 1 #=> true
+!true #=> false
+!false #=> true
+
+# Además de 'false', 'nil' es otro valor falso
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Más comparaciones
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Los strings son objetos
+
+'Soy un string'.class #=> String
+"Soy un string también".class #=> String
+
+referente = "usar interpolacion de strings"
+"Yo puedo #{referente} usando strings de comillas dobles"
+#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles"
+
+
+# Imprime a la salida estándar
+puts "¡Estoy imprimiendo!"
+
+# Variables
+x = 25 #=> 25
+x #=> 25
+
+# Nota que la asignación retorna el valor asignado
+# Esto significa que puedes hacer múltiples asignaciones:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Por convención, usa snake_case para nombres de variables
+snake_case = true
+
+# Usa nombres de variables descriptivos
+ruta_para_la_raiz_de_un_projecto = '/buen/nombre/'
+ruta = '/mal/nombre/'
+
+# Los símbolos (son objetos)
+# Los símbolos son inmutables, constantes reusables representadas internamente por un
+# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
+# valores específicos y significativos
+
+:pendiente.class #=> Symbol
+
+status = :pendiente
+
+status == :pendiente #=> true
+
+status == 'pendiente' #=> false
+
+status == :aprovado #=> false
+
+# Arreglos
+
+# Esto es un arreglo
+[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Arreglos pueden contener elementos de distintos tipos
+
+arreglo = [1, "hola", false] #=> => [1, "hola", false]
+
+# Arreglos pueden ser indexados
+# Desde el frente
+arreglo[0] #=> 1
+arreglo[12] #=> nil
+
+# Tal como la aritmética, el acceso como variable[índice]
+# es sólo azúcar sintáctica
+# para llamar el método [] de un objeto
+arreglo.[] 0 #=> 1
+arreglo.[] 12 #=> nil
+
+# Desde el final
+arreglo[-1] #=> 5
+
+# Con un índice de inicio y final
+arreglo[2, 4] #=> [3, 4, 5]
+
+# O con rango
+arreglo[1..3] #=> [2, 3, 4]
+
+# Añade elementos a un arreglo así
+arreglo << 6 #=> [1, 2, 3, 4, 5, 6]
+
+# Hashes son los diccionarios principales de Ruby con pares llave/valor.
+# Hashes se denotan con llaves:
+hash = {'color' => 'verde', 'numero' => 5}
+
+hash.keys #=> ['color', 'numero']
+
+# Hashes pueden buscar rápidamente una llave:
+hash['color'] #=> 'verde'
+hash['numero'] #=> 5
+
+# Preguntarle a un hash por una llave que no existe retorna 'nil':
+hash['nada aqui'] #=> nil
+
+# Itera sobre un hash con el método 'each':
+hash.each do |k, v|
+ puts "#{k} is #{v}"
+end
+
+# Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave:
+
+nuevo_hash = { defcon: 3, accion: true}
+
+nuevo_hash.keys #=> [:defcon, :accion]
+
+# Tip: Tanto los arreglos como los hashes son Enumerable (enumerables)
+# Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más
+
+# Estructuras de Control
+
+if true
+ "declaracion 'if'"
+elsif false
+ "else if, opcional"
+else
+ "else, tambien opcional"
+end
+
+for contador in 1..5
+ puts "iteracion #{contador}"
+end
+#=> iteracion 1
+#=> iteracion 2
+#=> iteracion 3
+#=> iteracion 4
+#=> iteracion 5
+
+# Aunque
+# Nadie usa los ciclos `for`
+# Usa `each`, así:
+
+(1..5).each do |contador|
+ puts "iteracion #{contador}"
+end
+#=> iteracion 1
+#=> iteracion 2
+#=> iteracion 3
+#=> iteracion 4
+#=> iteracion 5
+
+counter = 1
+while counter <= 5 do
+ puts "iteracion #{counter}"
+ counter += 1
+end
+#=> iteracion 1
+#=> iteracion 2
+#=> iteracion 3
+#=> iteracion 4
+#=> iteracion 5
+
+nota = 'B'
+
+case nota
+when 'A'
+ puts "Muy bien muchacho"
+when 'B'
+ puts "Mejor suerte para la proxima"
+when 'C'
+ puts "Puedes hacerlo mejor"
+when 'D'
+ puts "Sobreviviendo"
+when 'F'
+ puts "¡Reprobaste!"
+else
+ puts "Sistema alternativo de notas, ¿eh?"
+end
+
+# Funciones
+
+def doble(x)
+ x * 2
+end
+
+# Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción
+doble(2) #=> 4
+
+# Paréntesis son opcionales cuando el resultado es ambiguo
+doble 3 #=> 6
+
+doble doble 3 #=> 12
+
+def suma(x,y)
+ x + y
+end
+
+# Arguméntos del método son separados por coma
+suma 3, 4 #=> 7
+
+suma suma(3,4), 5 #=> 12
+
+# yield
+# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp
+# puede llamarse con la palabra clave 'yield'
+
+def alrededor
+ puts "{"
+ yield
+ puts "}"
+end
+
+alrededor { puts 'hola mundo' }
+
+# {
+# hola mundo
+# }
+
+
+# Define una clase con la palabra clave 'class'
+class Humano
+
+ # Una variable de clase. Es compartida por todas las instancias de la clase.
+ @@species = "H. sapiens"
+
+ # Inicializador Básico
+ def initialize(nombre, edad=0)
+ # Asigna el argumento a la variable de instancia 'nombre'
+ @nombre = nombre
+ # Si no dan edad, se usará el valor por defecto en la lista de argumentos.
+ @edad = edad
+ end
+
+ # Método 'setter' (establecer) básico
+ def nombre=(nombre)
+ @nombre = nombre
+ end
+
+ # Método 'getter' (obtener) básico
+ def nombre
+ @nombre
+ end
+
+ # Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia.
+ # Sólo puede ser llamado en la clase, no por una instancia.
+ def self.decir(mensaje)
+ puts "#{mensaje}"
+ end
+
+ def especie
+ @@especie
+ end
+
+end
+
+
+# Instancia una clase
+jim = Humano.new("Jim Halpert")
+
+dwight = Humano.new("Dwight K. Schrute")
+
+# Llamemos un par de métodos
+jim.especie #=> "H. sapiens"
+jim.nombre #=> "Jim Halpert"
+jim.nombre = "Jim Halpert II" #=> "Jim Halpert II"
+jim.nombre #=> "Jim Halpert II"
+dwight.especie #=> "H. sapiens"
+dwight.nombre #=> "Dwight K. Schrute"
+
+# Llama el método de clase
+Humano.decir("Hi") #=> "Hi"
+
+# Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia.
+# Variables de clase son compartidas a través de la clase y todos sus descendientes.
+
+# clase base
+class Humano
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(valor)
+ @@foo = valor
+ end
+end
+
+# clase derivada
+class Trabajador < Humano
+end
+
+Humano.foo # 0
+Trabajador.foo # 0
+
+Humano.foo = 2 # 2
+Trabajador.foo # 2
+
+# Las variables de instancia de la clase no son compartidas por los descendientes de la clase.
+
+class Humano
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(valor)
+ @bar = valor
+ end
+end
+
+class Doctor < Humano
+end
+
+Human.bar # 0
+Doctor.bar # nil
+
+```
diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown
new file mode 100644
index 00000000..e08bb5a8
--- /dev/null
+++ b/pt-br/python-pt.html.markdown
@@ -0,0 +1,509 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Vilson Vieira", "http://automata.cc"]
+lang: pt-bf
+filename: learnpython-pt.py
+---
+
+Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma
+das linguagens de programação mais populares. Eu me apaixonei por Python, por
+sua clareza de sintaxe. É basicamente pseudocódigo executável.
+
+Comentários serão muito apreciados! Você pode me contactar em
+[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba]
+[serviço de email do google]
+
+Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a
+qualquer Python 2.x. Logo haverá uma versão abordando Python 3!
+
+```python
+# Comentários de uma linha começam com cerquilha (ou sustenido)
+""" Strings de várias linhas podem ser escritas
+ usando três ", e são comumente usadas
+ como comentários
+"""
+
+####################################################
+## 1. Tipos de dados primitivos e operadores
+####################################################
+
+# Você usa números normalmente
+3 #=> 3
+
+# Operadores matemáticos são aqueles que você já está acostumado
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# A divisão é um pouco estranha. A divisão de números inteiros arredonda
+# para baixo o resultado, automaticamente
+5 / 2 #=> 2
+
+# Para concertar a divisão, precisamos aprender sobre números de ponto
+# flutuante (conhecidos como 'float').
+2.0 # Isso é um 'float'
+11.0 / 4.0 #=> 2.75 ahhh... muito melhor
+
+# Forçamos a precedência de operadores usando parênteses
+(1 + 3) * 2 #=> 8
+
+# Valores booleanos (ou 'boolean') são também tipos primitivos
+True
+False
+
+# Negamos usando 'not'
+not True #=> False
+not False #=> True
+
+# Testamos igualdade usando '=='
+1 == 1 #=> True
+2 == 1 #=> False
+
+# E desigualdade com '!='
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Mais comparações
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# As comparações podem ser encadeadas!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Strings são criadas com " ou '
+"Isso é uma string."
+'Isso também é uma string.'
+
+# Strings podem ser somadas (ou melhor, concatenadas)!
+"Olá " + "mundo!" #=> "Olá mundo!"
+
+# Uma string pode ser tratada como uma lista de caracteres
+"Esta é uma string"[0] #=> 'E'
+
+# O caractere % pode ser usado para formatar strings, desta forma:
+"%s podem ser %s" % ("strings", "interpoladas")
+
+# Um jeito novo de formatar strings é usando o método 'format'.
+# Esse método é o jeito mais usado
+"{0} podem ser {1}".format("strings", "formatadas")
+# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar.
+"{nome} quer comer {comida}".format(nome="João", comida="lasanha")
+
+# 'None' é um objeto
+None #=> None
+
+# Não use o operador de igualdade `==` para comparar objetos com 'None'
+# Ao invés disso, use `is`
+"etc" is None #=> False
+None is None #=> True
+
+# O operador 'is' teste a identidade de um objeto. Isso não é
+# muito útil quando estamos lidando com valores primitivos, mas é
+# muito útil quando lidamos com objetos.
+
+# None, 0, e strings/listas vazias são todas interpretadas como 'False'.
+# Todos os outros valores são 'True'
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Variáveis e Coleções
+####################################################
+
+# Imprimir na tela é muito fácil
+print "Eu sou o Python. Prazer em te conhecer!"
+
+
+# Nós não precisamos declarar variáveis antes de usá-las, basta usar!
+alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos
+alguma_variavel #=> 5
+
+# Acessar uma variável que não teve nenhum valor atribuído anteriormente é
+# uma exceção.
+# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção.
+outra_variavel # Gera uma exceção de erro de nome
+
+# 'if' pode ser usado como uma expressão
+"uepa!" if 3 > 2 else 2 #=> "uepa!"
+
+# Listas armazenam sequências de elementos
+lista = []
+# Você pode inicializar uma lista com valores
+outra_lista = [4, 5, 6]
+
+# Adicione elementos no final da lista usando 'append'
+lista.append(1) # lista é agora [1]
+lista.append(2) # lista é agora [1, 2]
+lista.append(4) # lista é agora [1, 2, 4]
+lista.append(3) # lista é agora [1, 2, 4, 3]
+# Remova elementos do fim da lista usando 'pop'
+lista.pop() #=> 3 e lista é agora [1, 2, 4]
+# Vamos adicionar o elemento novamente
+lista.append(3) # lista agora é [1, 2, 4, 3] novamente.
+
+# Acesse elementos de uma lista através de seu índices
+lista[0] #=> 1
+# Acesse o último elemento com índice negativo!
+lista[-1] #=> 3
+
+# Tentar acessar um elemento fora dos limites da lista gera uma exceção
+# do tipo 'IndexError'
+lista[4] # Gera uma exceção 'IndexError'
+
+# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de
+# limites
+# (Para quem gosta de matemática, isso é um limite fechado/aberto)
+lista[1:3] #=> [2, 4]
+# Você pode omitir o fim se quiser os elementos até o final da lista
+lista[2:] #=> [4, 3]
+# O mesmo para o início
+lista[:3] #=> [1, 2, 4]
+
+# Remova um elemento qualquer de uma lista usando 'del'
+del lista[2] # lista agora é [1, 2, 3]
+
+# Você pode somar listas (obs: as listas originais não são modificadas)
+lista + outra_lista #=> [1, 2, 3, 4, 5, 6]
+
+# Você também pode concatenar usando o método 'extend' (lista será modificada!)
+lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6]
+
+# Para checar se um elemento pertence a uma lista, use 'in'
+1 in lista #=> True
+
+# Saiba quantos elementos uma lista possui com 'len'
+len(lista) #=> 6
+
+
+# Tuplas são iguais a listas, mas são imutáveis
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Isso gera uma exceção do tipo TypeError
+
+# Você pode fazer nas tuplas todas aquelas coisas fez com a lista
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada
+# elemento da tupla/lista a uma variável correspondente
+a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3
+# Tuplas são criadas por padrão, mesmo se você não usar parênteses
+d, e, f = 4, 5, 6
+# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis!
+e, d = d, e # d agora é 5, e agora é 4
+
+
+# Dicionários armazenam 'mapeamentos' (do tipo chave-valor)
+dicionario_vazio = {}
+# Aqui criamos um dicionário já contendo valores
+dicionario = {"um": 1, "dois": 2, "três": 3}
+
+# Acesse valores usando []
+dicionario["um"] #=> 1
+
+# Retorna uma lista com todas as chaves do dicionário
+dicionario.keys() #=> ["três", "dois", "um"]
+# Nota: A ordem das chaves não é garantida.
+# O resultado no seu interpretador não necessariamente será igual a esse.
+
+# Retorna uma lista com todos os valores do dicionário
+dicionario.values() #=> [3, 2, 1]
+# Nota: A mesma nota acima sobre a ordenação é válida aqui.
+
+# Veja se uma chave qualquer está em um dicionário usando 'in'
+"um" in dicionario #=> True
+1 in dicionario #=> False
+
+# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError'
+dicionario["quatro"] # Gera uma exceção KeyError
+
+# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'.
+# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir.
+dicionario.get("um") #=> 1
+dicionario.get("quatro") #=> None
+# O método 'get' suporta um argumento que diz qual valor deverá ser
+# retornado se a chave não existir (ao invés de 'None').
+dicionario.get("um", 4) #=> 1
+dicionario.get("quatro", 4) #=> 4
+
+# O método 'setdefault' é um jeito seguro de adicionar um novo par
+# chave-valor a um dicionário, associando um valor padrão imutável à uma chave
+dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5
+dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5
+
+
+# Conjuntos (ou sets) armazenam ... bem, conjuntos
+# Nota: lembre-se que conjuntos não admitem elementos repetidos!
+conjunto_vazio = set()
+# Podemos inicializar um conjunto com valores
+conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição!
+
+# Desde o Python 2.7, {} pode ser usado para declarar um conjunto
+conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Adicione mais ítens a um conjunto com 'add'
+conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5}
+
+# Calcule a intersecção de dois conjuntos com &
+outro_conj = {3, 4, 5, 6}
+conjunto & outro_conj #=> {3, 4, 5}
+
+# Calcule a união de dois conjuntos com |
+conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6}
+
+# E a diferença entre dois conjuntos com -
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Veja se um elemento existe em um conjunto usando 'in'
+2 in conjunto #=> True
+10 in conjunto #=> False
+
+
+####################################################
+## 3. Controle
+####################################################
+
+# Para começar, vamos apenas criar uma variável
+alguma_var = 5
+
+# Aqui está uma expressão 'if'. Veja como a identação é importante em Python!
+# Esses comandos irão imprimir "alguma_var é menor que 10"
+if alguma_var > 10:
+ print "some_var é maior que 10."
+elif some_var < 10: # Esse 'elif' é opcional
+ print "some_var é menor que 10."
+else: # Esse 'else' também é opcional
+ print "some_var é igual a 10."
+
+
+"""
+Laços (ou loops) 'for' iteram em listas.
+Irá imprimir:
+ cachorro é um mamífero
+ gato é um mamífero
+ rato é um mamífero
+"""
+for animal in ["cachorro", "gato", "rato"]:
+ # Você pode usar % para interpolar strings formatadas
+ print "%s é um mamífero" % animal
+
+"""
+A função `range(um número)` retorna uma lista de números
+do zero até o número dado.
+Irá imprimir:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+Laços 'while' executam enquanto uma condição dada for verdadeira.
+Irá imprimir:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Isso é um atalho para a expressão x = x + 1
+
+# Tratamos excessões usando o bloco try/except
+# Funciona em Python 2.6 e versões superiores:
+
+try:
+ # Use 'raise' para gerar um erro
+ raise IndexError("Isso é um erro de índice")
+except IndexError as e:
+ pass # Pass é um operador que não faz nada, deixa passar.
+ # Usualmente você iria tratar a exceção aqui...
+
+
+####################################################
+## 4. Funções
+####################################################
+
+# Use 'def' para definir novas funções
+def soma(x, y):
+ print "x é %s e y é %s" % (x, y)
+ return x + y # Retorne valores usando 'return'
+
+# Chamando funções com parâmetros
+soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11
+
+# Um outro jeito de chamar funções é especificando explicitamente os valores
+# de cada parâmetro com chaves
+soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem.
+
+# Você pode definir funções que recebem um número qualquer de argumentos
+# (respeitando a sua ordem)
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+
+# Você também pode definir funções que recebem um número qualquer de argumentos
+# com chaves
+def args_com_chaves(**ch_args):
+ return ch_args
+
+# Vamos chamar essa função para ver o que acontece
+args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"}
+
+# Você pode fazer as duas coisas ao mesmo tempo, se desejar
+def todos_args(*args, **ch_wargs):
+ print args
+ print ch_args
+"""
+todos_args(1, 2, a=3, b=4) imprime:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Quando você chamar funções, pode fazer o oposto do que fizemos até agora!
+# Podemos usar * para expandir tuplas de argumentos e ** para expandir
+# dicionários de argumentos com chave.
+args = (1, 2, 3, 4)
+ch_args = {"a": 3, "b": 4}
+todos_args(*args) # equivalente a todos_args(1, 2, 3, 4)
+todos_args(**ch_args) # equivalente a todos_args(a=3, b=4)
+todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4)
+
+# Em Python, funções são elementos de primeira ordem (são como objetos,
+# strings ou números)
+def cria_somador(x):
+ def somador(y):
+ return x + y
+ return somador
+
+soma_10 = cria_somador(10)
+soma_10(3) #=> 13
+
+# Desta forma, existem também funções anônimas
+(lambda x: x > 2)(3) #=> True
+
+# E existem funções de alta ordem por padrão
+map(soma_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25
+
+# Nós podemos usar compreensão de listas para mapear e filtrar também
+[soma_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+####################################################
+## 5. Classes
+####################################################
+
+# Para criar uma nova classe, devemos herdar de 'object'
+class Humano(object):
+
+ # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa
+ # classe
+ especie = "H. sapiens"
+
+ # Definimos um inicializador básico
+ def __init__(self, nome):
+ # Atribui o valor de argumento dado a um atributo da instância
+ self.nome = nome
+
+ # Um método de instância. Todos os métodos levam 'self' como primeiro
+ # argumento
+ def diga(self, msg):
+ return "%s: %s" % (self.nome, msg)
+
+ # Um método de classe é compartilhado por todas as instâncias
+ # Eles são chamados passando o nome da classe como primeiro argumento
+ @classmethod
+ def get_especie(cls):
+ return cls.especie
+
+ # Um método estático é chamado sem uma referência a classe ou instância
+ @staticmethod
+ def ronca():
+ return "*arrrrrrr*"
+
+
+# Instancie uma classe
+i = Humano(nome="Ivone")
+print i.diga("oi") # imprime "Ivone: oi"
+
+j = Human("Joel")
+print j.say("olá") #prints out "Joel: olá"
+
+# Chame nosso método de classe
+i.get_especie() #=> "H. sapiens"
+
+# Modifique um atributo compartilhado
+Humano.especie = "H. neanderthalensis"
+i.get_especie() #=> "H. neanderthalensis"
+j.get_especie() #=> "H. neanderthalensis"
+
+# Chame o método estático
+Humano.ronca() #=> "*arrrrrrr*"
+
+
+####################################################
+## 6. Módulos
+####################################################
+
+# Você pode importar módulos
+import math
+print math.sqrt(16) #=> 4
+
+# Você pode importar funções específicas de um módulo
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Você também pode importar todas as funções de um módulo
+# Atenção: isso não é recomendado!
+from math import *
+
+# Você pode usar apelidos para os módulos, encurtando seus nomes
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Módulos em Python são apenas arquivos Python. Você
+# pode escrever o seu próprio módulo e importá-lo. O nome do
+# módulo será o mesmo que o nome do arquivo.
+
+# Você pode descobrir quais funções e atributos
+# estão definidos em um módulo qualquer.
+import math
+dir(math)
+
+
+```
+
+## Pronto para mais?
+
+### Online e gratuito
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Livros impressos
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/r.html.markdown b/r.html.markdown
index dd94072b..03aa1dd2 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -2,6 +2,7 @@
language: R
contributors:
- ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
filename: learnr.r
---
@@ -296,14 +297,13 @@ if (4 > 3) {
# FUNCTIONS
# Defined like so:
-myFunc <- function(x) {
- x <- x * 4
- x <- x - 1
+jiggle <- function(x) {
+ x+ rnorm(x, sd=.1) #add in a bit of (controlled) noise
return(x)
}
# Called like any other R function:
-myFunc(5) # 19
+jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
#########################
# Fun with data: vectors, matrices, data frames, and arrays
@@ -428,15 +428,17 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
# =>
# , , 1
#
-# [,1] [,2]
-# [1,] 1 4
-# [2,] 2 5
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
#
# , , 2
#
# [,1] [,2]
-# [1,] 8 1
-# [2,] 9 2
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES)
diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown
new file mode 100644
index 00000000..a31f552d
--- /dev/null
+++ b/ruby-ecosystem.html.markdown
@@ -0,0 +1,137 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+
+---
+
+People using ruby generally have a way to install different ruby versions,
+manage their packages (or gems), and manage their gem dependencies.
+
+## Ruby Managers
+
+Some platforms have ruby pre-installed or available as a package. Most rubyists
+do not use these, or if they do, they only use them to bootstrap another ruby
+installer or implementation. Instead rubyists tend to install a ruby manager to
+install and switch between many versions of ruby and their projects' ruby
+environments.
+
+The following are the popular ruby/environment managers:
+
+* [RVM](https://rvm.io/) - Installs and switches between rubies. RVM also has
+ the concept of gemsets to isolate projects' environments completely.
+* [ruby-build](https://github.com/sstephenson/ruby-build) - Only installs
+ rubies. Use this for finer control over your rubies' installations.
+* [rbenv](https://github.com/sstephenson/rbenv) - Only switches between rubies.
+ Used with ruby-build. Use this for finer control over how rubies load.
+* [chruby](https://github.com/postmodern/chruby) - Only switches between rubies.
+ Similar in spirit to rbenv. Unopinionated about how rubies are installed.
+
+## Ruby Versions
+
+Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a
+[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although
+that is changing recently. As a result, the reference implementation of ruby is
+called MRI (Matz' Reference Implementation), and when you hear a ruby version,
+it is referring to the release version of MRI.
+
+The three major version of ruby in use are:
+
+* 2.0.0 - Released in February 2013. Most major libraries and frameworks support
+ 2.0.0.
+* 1.9.3 - Released in October 2011. This is the version most rubyists use
+ currently.
+* 1.8.7 - Ruby 1.8.7 has been
+ [retired](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+The change between 1.8.7 to 1.9.x is a much larger change than 1.9.3 to 2.0.0.
+For instance, the 1.9 series introduced encodings and a bytecode VM. There
+are projects still on 1.8.7, but they are becoming a small minority, as most of
+the community has moved to at least 1.9.2 or 1.9.3.
+
+## Ruby Implementations
+
+The ruby ecosystem enjoys many different implementations of ruby, each with
+unique strengths and states of compatability. To be clear, the different
+implementations are written in different languages, but *they are all ruby*.
+Each implementation has special hooks and extra features, but they all run
+normal ruby files well. For instance, JRuby is written in Java, but you do
+not need to know Java to use it.
+
+Very mature/compatible:
+
+* MRI - Written in C, this is the reference implementation of ruby. By
+ definition it is 100% compatible (with itself). All other rubies
+maintain capatability with MRI (see RubySpec below).
+* JRuby - Written in Java and ruby, this robust implementation is quite fast.
+ Most importantly, JRuby's strength is JVM/Java interop, leveraging existing
+JVM tools, projects, and languages.
+* Rubinius - Written primarily in ruby itself with a C++ bytecode VM. Also
+ mature and fast. Because it is implemented in ruby itself, it exposes many VM
+features into rubyland.
+
+Medium mature/compatible:
+
+* Maglev - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some
+ impressive tooling, and this project tries to bring that into ruby
+development.
+* RubyMotion - Brings ruby to iOS development.
+
+Less mature/compatible:
+
+* Topaz - Written in RPython (using the PyPy toolchain), Topaz is fairly young
+ and not yet compatable. It shows promise to be a high-performance ruby
+implementation.
+* IronRuby - Written in C# targeting the .NET platform, work on IronRuby seems
+ to have stopped since Microsoft pulled their support.
+
+Ruby implementations may have their own release version numbers, but they always
+target a specific version of MRI for compatability. Many implementations have
+the ability to enter different modes (for example, 1.8 or 1.9 mode) to specify
+which MRI version to target.
+
+## RubySpec
+
+Most ruby implementations rely heavily on (RubySpec)[http://rubyspec.org/]. Ruby
+has no official specification, so the community has written executable specs in
+ruby to test their implementations' compatability with MRI.
+
+## RubyGems
+
+(RubyGems)[http://rubygems.org/] is a community-run package manager for ruby.
+RubyGems ships with ruby, so there is no need to download it separately.
+
+Ruby packages are called "gems," and they can be hosted by the community at
+RubyGems.org. Each gem contains its source code and some metadata, including
+things like version, dependencies, author(s), and license(s).
+
+## Bundler
+
+(Bundler)[http://bundler.io/] is a gem dependency resolver. It uses a project's
+Gemfile to find dependencies, and then fetches those dependencies' dependencies
+recursively. It does this until all dependencies are resolved and downloaded, or
+it will stop if a conflict has been found.
+
+Bundler will raise an error if it finds conflicting dependencies. For example,
+if gem A requires version 3 or greater of gem Z, but gem B requires version 2,
+Bundler will notify you of the conflict. This becomes extremely helpful as many
+gems refer to other gems (which refer to other gems), which can form a large
+dependency graph to resolve.
+
+# Testing
+
+Testing is a large of ruby culture. Ruby comes with its own Unit-style testing
+framework called minitest (Or TestUnit for ruby version 1.8.x). There are many
+testing libraries with different goals.
+
+* TestUnit - Ruby 1.8's built-in "Unit-style" testing framework
+* minitest - Ruby 1.9/2.0's built-in testing framework
+* RSpec - A testing framework that focuses on expressivity
+* Cucumber - A BDD testing framework that parses Gherkin formatted tests
+
+## Be Nice
+
+The ruby community takes pride in being an open, diverse, welcoming community.
+Matz himself is extremely friendly, and the generosity of rubyists on the whole
+is amazing.
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index f8a8e0bd..b4bff8fc 100755
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -1,6 +1,6 @@
---
language: c
-filename: learnc.c
+filename: learnc-cn.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
translators:
diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown
index 64663b21..6a6562bc 100644
--- a/zh-cn/dart-cn.html.markdown
+++ b/zh-cn/dart-cn.html.markdown
@@ -1,6 +1,7 @@
---
language: dart
-filename: learndart.dart
+lang: zh-cn
+filename: learndart-cn.dart
contributors:
- ["Joao Pedrosa", "https://github.com/jpedrosa/"]
translators:
diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown
index c3a2f927..d303c2e8 100755
--- a/zh-cn/elisp-cn.html.markdown
+++ b/zh-cn/elisp-cn.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Bastien Guerry", "http://bzg.fr"]
translators:
- ["Chenbo Li", "http://binarythink.net"]
-filename: learn-emacs-lisp.el
+filename: learn-emacs-lisp-zh.el
lang: zh-cn
---
diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown
index 8c24f0b8..86952eba 100755
--- a/zh-cn/git-cn.html.markdown
+++ b/zh-cn/git-cn.html.markdown
@@ -5,7 +5,6 @@ contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
translators:
- ["Chenbo Li", "http://binarythink.net"]
-filename: LearnGit.txt
lang: zh-cn
---
diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index cb0de467..8d51f144 100755
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -1,6 +1,6 @@
---
language: haskell
-filename: learn-haskell.hs
+filename: learn-haskell-zh.hs
contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
@@ -404,4 +404,4 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
你可以从优秀的
[Learn you a Haskell](http://learnyouahaskell.com/) 或者
[Real World Haskell](http://book.realworldhaskell.org/)
-找到优雅不少的入门介绍。 \ No newline at end of file
+找到优雅不少的入门介绍。
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index b9ccf61a..9422ac2f 100755
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -3,7 +3,7 @@ name: java
category: language
language: java
lang: zh-cn
-filename: LearnJava.java
+filename: LearnJava-zh.java
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
translators:
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index 3b5cfa94..89fc256e 100755
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -2,6 +2,7 @@
language: javascript
category: language
name: javascript
+filename: javascript-zh.js
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
translators:
diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown
index 3b242ce1..c6ebb515 100755
--- a/zh-cn/php-cn.html.markdown
+++ b/zh-cn/php-cn.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["Chenbo Li", "http://binarythink.net"]
-filename: learnphp.php
+filename: learnphp-zh.php
lang: zh-cn
---
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index 259e4ed8..764eed54 100755
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
translators:
- ["Chenbo Li", "http://binarythink.net"]
-filename: learnpython.py
+filename: learnpython-zh.py
lang: zh-cn
---
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index f66d1a03..6530b520 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -1,6 +1,7 @@
---
language: ruby
-filename: learnruby.rb
+filename: learnruby-zh.rb
+lang: zh-cn
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown
new file mode 100644
index 00000000..1ce41ac6
--- /dev/null
+++ b/zh-cn/scala-cn.html.markdown
@@ -0,0 +1,413 @@
+---
+language: Scala
+filename: learnscala-zh.scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+translators:
+ - ["Peiyong Lin", ""]
+filename: learn.scala
+lang: zh-cn
+---
+
+Scala - 一门可拓展性的语言
+
+```cpp
+
+/*
+ 自行设置:
+
+ 1) 下载 Scala - http://www.scala-lang.org/downloads
+ 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下
+ 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符:
+
+ scala>
+
+ 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点:
+*/
+
+println(10) // 打印整数 10
+
+println("Boo!") // 打印字符串 "BOO!"
+
+
+// 一些基础
+
+// 打印并强制换行
+println("Hello world!")
+// 没有强制换行的打印
+print("Hello world")
+
+// 通过 var 或者 val 来声明变量
+// val 声明是不可变的,var 声明是可修改的。不可变性是好事。
+val x = 10 // x 现在是 10
+x = 20 // 错误: 对 val 声明的变量重新赋值
+var x = 10
+x = 20 // x 现在是 20
+
+// 单行注释开始于两个斜杠
+/*
+多行注释看起来像这样。
+*/
+
+// 布尔值
+true
+false
+
+// 布尔操作
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+// 数学运算像平常一样
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+
+
+// 在 REPL 计算一个命令会返回给你结果的类型和值
+
+1 + 7
+
+/* 上行的结果是:
+
+ scala> 1 + 7
+ res29: Int = 8
+
+ 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8
+
+ 1+7 的结果是一样的
+*/
+
+
+// 包括函数在内,每一个事物都是对象。在 REPL 中输入:
+
+7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名)
+
+// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数
+(x:Int) => x * x
+
+// 你可以分配给函数一个标识符,像这样:
+val sq = (x:Int) => x * x
+
+/* 上面的例子说明
+
+ sq: Int => Int = <function1>
+
+ 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数
+
+ sq 可以像下面那样被执行:
+*/
+
+sq(10) // 返回给你:res33: Int = 100.
+
+// Scala 允许方法和函数返回或者接受其它的函数或者方法作为参数。
+
+val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数
+List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素
+
+// 匿名函数可以被使用来代替有命名的函数:
+List(1, 2, 3) map (x => x + 10)
+
+// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量
+List(1, 2, 3) map (_ + 10)
+
+// 如果你所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线
+List("Dom", "Bob", "Natalia") foreach println
+
+
+
+// 数据结构
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // 这会抛出一个异常
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // 这会抛出一个异常
+
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+val s = Set(1, 3, 7)
+s(0)
+s(1)
+
+/* 查看 map 的文档
+ * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map)
+ * 确保你可以读它
+ */
+
+
+// 元组
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "three")
+
+(a, 2, "three")
+
+// 为什么有这个?
+
+val divideInts = (x:Int, y:Int) => (x / y, x % y)
+
+divideInts(10,3) // 函数 divideInts 返回你结果和余数
+
+// 要读取元组的元素,使用 _._n,n是从1开始的元素索引
+
+val d = divideInts(10,3)
+
+d._1
+
+d._2
+
+
+
+// 选择器
+
+s.map(sq)
+
+val sSquared = s. map(sq)
+
+sSquared.filter(_ < 10)
+
+sSquared.reduce (_+_)
+
+// filter 函数接受一个预测(一个函数,形式为 A -> Boolean) 并选择出所有的元素满足这个预测
+
+List(1, 2, 3) filter (_ > 2) // List(3)
+List(
+ Person(name = "Dom", age = 23),
+ Person(name = "Bob", age = 30)
+).filter(_.age > 25) // List(Person("Bob", 30))
+
+
+// Scala 的 foreach 方法定义在特定的接受一个类型的集合上
+// 返回 Unit(一个 void 方法)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+
+
+
+// For 包含
+
+for { n <- s } yield sq(n)
+
+val nSquared2 = for { n <- s } yield sq(n)
+
+for { n <- nSquared2 if n < 10 } yield n
+
+for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+
+/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'),
+ 然而,一个 for-包含 定义了一个两个数据结合间的关系 */
+
+
+
+// 循环和迭代
+
+1 to 5
+val r = 1 to 5
+r.foreach( println )
+
+r foreach println
+// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。
+// 这帮助你编写读起来像英语的 DSLs 和 APIs
+
+(5 to 1 by -1) foreach ( println )
+
+// while 循环
+var i = 0
+while (i < 10) { println("i " + i); i+=1 }
+
+while (i < 10) { println("i " + i); i+=1 } // 发生了什么?为什么?
+
+i // 展示 i 的值。注意到 while 是一个传统意义上的循环
+ // 它顺序地执行并且改变循环变量的值。while 非常快,比 Java // 循环快,
+ // 但是在其上使用选择器和包含更容易理解和并行。
+
+// do while 循环
+do {
+ println("x is still less then 10");
+ x += 1
+} while (x < 10)
+
+// 在 Scala中,尾递归是一种惯用的执行循环的方式。
+// 递归函数需要显示的返回类型,编译器不能推断出类型。
+// 这里它是 Unit。
+def showNumbersInRange(a:Int, b:Int):Unit = {
+ print(a)
+ if (a < b)
+ showNumbersInRange(a + 1, b)
+}
+
+
+
+// 条件语句
+
+val x = 10
+
+if (x == 1) println("yeah")
+if (x == 10) println("yeah")
+if (x == 11) println("yeah")
+if (x == 11) println ("yeah") else println("nay")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+var i = 0
+while (i < 10) { println("i " + i); i+=1 }
+
+
+
+// 面向对象特性
+
+// 类名是 Dog
+class Dog {
+ //bark 方法,返回字符串
+ def bark: String = {
+ // the body of the method
+ "Woof, woof!"
+ }
+}
+
+// 类可以包含几乎其它的构造,包括其它的类,
+// 函数,方法,对象,case 类,特性等等。
+
+
+
+// Case 类
+
+case class Person(name:String, phoneNumber:String)
+
+Person("George", "1234") == Person("Kate", "1236")
+
+
+
+
+// 模式匹配
+
+val me = Person("George", "1234")
+
+me match { case Person(name, number) => {
+ "We matched someone : " + name + ", phone : " + number }}
+
+me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." }
+
+me match { case Person("George", number) => "Match"; case _ => "Hm..." }
+
+me match { case Person("Kate", number) => "Match"; case _ => "Hm..." }
+
+me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
+
+val kate = Person("Kate", "1234")
+
+kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
+
+
+
+// 正则表达式
+
+val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式
+
+val email(user, domain) = "henry@zkpr.com"
+
+"mrbean@pyahoo.com" match {
+ case email(name, domain) => "I know your name, " + name
+}
+
+
+
+// 字符串
+
+"Scala 字符串被双引号包围" //
+'a' // Scala 字符
+'单引号的字符串不存在' // 错误
+"字符串拥有通常的 Java 方法定义在其上".length
+"字符串也有额外的 Scala 方法".reverse
+
+// 参见: scala.collection.immutable.StringOps
+
+println("ABCDEF".length)
+println("ABCDEF".substring(2, 6))
+println("ABCDEF".replace("C", "3"))
+
+val n = 45
+println(s"We have $n apples")
+
+val a = Array(11, 9, 6)
+println(s"My second daughter is ${a(2-1)} years old")
+
+// 一些字符需要被转义,举例来说,字符串中的双引号:
+val a = "They stood outside the \"Rose and Crown\""
+
+// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义)
+
+val html = """<form id="daform">
+ <p>Press belo', Joe</p>
+ | <input type="submit">
+ </form>"""
+
+
+
+// 应用结果和组织
+
+// import
+import scala.collection.immutable.List
+
+// Import 所有的子包
+import scala.collection.immutable._
+
+// 在一条语句中 Import 多个类
+import scala.collection.immutable.{List, Map}
+
+// 使用 '=>' 来重命名一个 import
+import scala.collection.immutable{ List => ImmutableList }
+
+// import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类:
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义:
+
+object Application {
+ def main(args: Array[String]): Unit = {
+ // stuff goes here.
+ }
+}
+
+// 文件可以包含多个类和对象。由 scalac 来编译
+
+
+
+
+// 输入和输出
+
+// 一行一行读取文件
+import scala.io.Source
+for(line <- Source.fromPath("myfile.txt").getLines())
+ println(line)
+
+// 使用 Java 的 PrintWriter 来写文件
+
+
+```
+
+## 更多的资源
+
+[为没耐心的人准备的 Scala](http://horstmann.com/scala/)
+
+[Twitter Scala school](http://twitter.github.io/scala_school/)
+
+[The Scala documentation](http://www.scala-lang.org/documentation/)
+
+[在浏览器尝试 Scala](http://scalatutorials.com/tour/)
+
+加入 [Scala 用户组](https://groups.google.com/forum/#!forum/scala-user)