diff options
-rw-r--r-- | Visual Basic | 248 | ||||
-rw-r--r-- | php.html.markdown | 5 | ||||
-rw-r--r-- | scala.html.markdown | 416 | ||||
-rwxr-xr-x | zh-cn/git-cn.html.markdown | 375 | ||||
-rwxr-xr-x | zh-cn/haskell-cn.html.markdown | 407 | ||||
-rwxr-xr-x | zh-cn/javascript-cn.html.markdown (renamed from zh-cn/javascript.html.markdown) | 0 | ||||
-rwxr-xr-x | zh-cn/python-cn.html.markdown | 475 | ||||
-rw-r--r-- | zh-cn/ruby-cn.html.markdown | 329 |
8 files changed, 2005 insertions, 250 deletions
diff --git a/Visual Basic b/Visual Basic deleted file mode 100644 index 73430633..00000000 --- a/Visual Basic +++ /dev/null @@ -1,248 +0,0 @@ ---- -language: Visual Basic Console Application -contributors: - - ["Brian Martin", "http://brianmartin.biz"] -filename: learnvisualbasic.vb - -Module Module1 - - Sub Main() - 'A Quick Overview of Visual Basic Console Applications before we dive in to the deep end. - 'Apostrophe starts comments. - 'To Navigate this tutorial within the Visual Basic Complier, I've put together a navigation system. - 'This navigation system is explained however as we go deeper into this tutorial, you'll understand what it all means. - Console.Title = ("Learn X in Y Minutes") - Console.WriteLine("NAVIGATION") 'Display - Console.WriteLine("") - Console.ForegroundColor = ConsoleColor.Green - Console.WriteLine("1. Hello World Output") - Console.WriteLine("2. Hello World Input") - Console.WriteLine("3. Calculating Whole Numbers") - Console.WriteLine("4. Calculating Decimal Numbers") - Console.WriteLine("5. Working Calculator") - Console.WriteLine("6. Using Do While Loops") - Console.WriteLine("7. Using For While Loops") - Console.WriteLine("8. Conditional Statements") - Console.WriteLine("9. Select A Drink") - Console.WriteLine("50. About") - Console.WriteLine("Please Choose A Number From The Above List") - Dim selection As String = Console.ReadLine - Select Case selection - Case "1" 'HelloWorld Output - Console.Clear() 'Clears the application and opens the private sub - HelloWorldOutput() 'Name Private Sub, Opens Private Sub - Case "2" 'Hello Input - Console.Clear() - HelloWorldInput() - Case "3" 'Calculating Whole Numbers - Console.Clear() - CalculatingWholeNumbers() - Case "4" 'Calculting Decimal Numbers - Console.Clear() - CalculatingDecimalNumbers() - Case "5" 'Working Calcculator - Console.Clear() - WorkingCalculator() - Case "6" 'Using Do While Loops - Console.Clear() - UsingDoWhileLoops() - Case "7" 'Using For While Loops - Console.Clear() - UsingForLoops() - Case "8" 'Conditional Statements - Console.Clear() - ConditionalStatement() - Case "9" 'If/Else Statement - Console.Clear() - IfElseStatement() 'Select a drink - Case "50" 'About msg box - Console.Clear() - Console.Title = ("Learn X in Y Minutes :: About") - MsgBox("Learn X in Y Minutes is a creation of Adam Bard (@adambard) This particular program tutorial is by Brian Martin (@BrianMartinn") - Console.Clear() - Main() - Console.ReadLine() - - End Select - End Sub - - 'One - I'm using numbers to help with the above navigation when I come back later to build it. - Private Sub HelloWorldOutput() 'We use private subs to seperate different sections of the program. - Console.Title = "Hello World Ouput | Learn X in Y Minutes" 'Title of Console Application - 'Use Console.Write("") or Console.WriteLine("") to print outputs. - 'Followed by Console.Read() alternatively Console.Readline() - 'Console.ReadLine() prints the output to the console. - Console.WriteLine("Hello World") - Console.ReadLine() - End Sub - 'Two - Private Sub HelloWorldInput() 'We use private subs to seperate different sections of the program. - Console.Title = "Hello World YourName | Learn X in Y Minutes" 'Title of Console Application - 'Variables - 'Data entered by a user needs to be stored. - 'Variables also start with a Dim and end with an As VariableType. - Dim username As String 'In this tutorial, we want to know what your name, and make the program respond to what is said. - 'We use string as string is a text based variable. - Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. - username = Console.ReadLine() 'Stores the users name. - Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' - Console.ReadLine() 'Outsputs the above. - 'The above will ask you a question followed by printing your answer. - 'Other variables include Integer and we use Integer for whole numbers. - End Sub - 'Three - Private Sub CalculatingWholeNumbers() 'We use private subs to seperate different sections of the program. - Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" 'Title of Console Application - Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect - Dim a As Integer = Console.ReadLine() - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine() - Dim c As Integer = a + b - Console.WriteLine(c) - Console.ReadLine() - 'The above is a simple calculator - End Sub - 'Four - Private Sub CalculatingDecimalNumbers() - Console.Title = "Calculating with Double | Learn X in Y Minutes" 'Title of Console Application - 'Of course we would like to be able to add up decimals. - 'Therefore we could change the above from Integer to Double. - Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Double = Console.ReadLine - Dim c As Double = a + b - Console.WriteLine(c) - Console.ReadLine() - 'Therefore the above program can add up 1.1 - 2.2 - End Sub - 'Five - Private Sub WorkingCalculator() - Console.Title = "The Working Calculator| Learn X in Y Minutes" 'Title of Console Application - 'However if you'd like the calculator to subtract, divide, multiple and add up. - 'Copy and paste the above again. - Console.Write("First number: ") 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b - 'By adding the below lines we are able to calculate the subtract, multply as well as divide the a and b values - Console.Write(a.ToString() + " + " + b.ToString()) - Console.WriteLine(" = " + c.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " * " + b.ToString()) - Console.WriteLine(" = " + d.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " - " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) 'We want to pad the answers to the left by 3 spaces. - Console.ReadLine() - - End Sub - 'Six - Private Sub UsingDoWhileLoops() - 'Just as the previous private sub - 'This Time We Ask If The User Wishes To Continue (Yes or No?) - 'We're using Do While Loop as we're unsure if the user wants to use the program more than once. - Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" - Dim answer As String 'We use the variable "String" as the answer is text - Do 'We start the program with - Console.Write("First number: ") - Dim a As Double = Console.ReadLine - Console.Write("Second number: ") - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b - - Console.Write(a.ToString() + " + " + b.ToString()) - Console.WriteLine(" = " + c.ToString.PadLeft(3)) - Console.Write(a.ToString() + " * " + b.ToString()) - Console.WriteLine(" = " + d.ToString.PadLeft(3)) - Console.Write(a.ToString() + " - " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) - Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) - Console.ReadLine() - 'Ask the question, does the user wish to continue? Unfortunately it is case sensitive. - Console.Write("Would you like to continue? (yes / no)") - answer = Console.ReadLine 'The program grabs the variable and prints and starts again. - Loop While answer = "yes" 'The command for the variable to work would be in this case "yes" - - End Sub - 'Seven - Private Sub UsingForLoops() - 'Sometimes the program only needs to run once. - 'In this program we'll be counting down from 10. - - Console.Title = "Using For Loops | Learn X in Y Minutes" - For i As Integer = 10 To 0 Step -1 'Declare Vairable and what number it should count down in Step -1, Step -2, Step -3 ect. - Console.WriteLine(i.ToString) 'Print the value of the counter variable - Next i 'Calculate new value - Console.WriteLine("Start") 'Lets start the program baby!! - Console.ReadLine() 'POW!! - Perhaps I got a little excited then :) - End Sub - 'Eight - Private Sub ConditionalStatement() - Console.Title = "Conditional Statements | Learn X in Y Minutes" - Dim userName As String = Console.ReadLine - Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. - userName = Console.ReadLine() 'Stores the users name. - If userName = "Adam" Then 'Hey, if Adam uses this program, kudos where kudos is due, right? - Console.WriteLine("Hello Adam") - Console.WriteLine("Thanks for creating the useful tutorial site www.learnxinyminutes.com!") - Console.ReadLine() - Else - Console.WriteLine("Hello " + userName) 'prints the username of the user - Console.WriteLine("Hope all is well have you checked out www.learnxinyminutes.com") 'Prints a message to the user - Console.ReadLine() 'Ends and prints the above statement. - End If - End Sub - 'Nine - Private Sub IfElseStatement() - Console.Title = "If / Else Statement | Learn X in Y Minutes" - 'Sometimes its important to consider more than two alternatives. Sometimes there are a good few others. - 'When this is the case, more than one if statement would be required. - 'An if statement is great for vending machines. Where the user enters a code. - 'A1, A2, A3, ect to select an item. - 'All choices can be combined into a single if statement. - - Dim selection As String = Console.ReadLine 'Value for selection - Console.WriteLine("A1. for 7Up") - Console.WriteLine("A2. for Fanta") - Console.WriteLine("A3. for Dr. Pepper") - Console.WriteLine("A4. for Diet Coke") - Console.ReadLine() - If selection = "A1" Then - Console.WriteLine("7up") - Console.ReadLine() - ElseIf selection = "A2" Then - Console.WriteLine("fanta") - Console.ReadLine() - ElseIf selection = "A3" Then - Console.WriteLine("dr. pepper") - Console.ReadLine() - ElseIf selection = "A4" Then - Console.WriteLine("diet coke") - Console.ReadLine() - Else - Console.WriteLine("Please select a product") - Console.ReadLine() - End If - - End Sub - -End Module - - -``` -## References - -I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. - -I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more. - -The entire syntax is valid. Copy the and paste in to the Visual Basic complier and run (F5) the program. diff --git a/php.html.markdown b/php.html.markdown index 5f5a4b54..ce228870 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -9,7 +9,7 @@ filename: learnphp.php This document describes PHP 5+. ```php -<?php // PHP code must be enclosed with <?php ?> tags +<?php // PHP code must be enclosed with <?php tags // If your php file only contains PHP code, it is best practise // to omit the php closing tag. @@ -31,7 +31,8 @@ echo "World\n"; // Prints "World" with a line break // (all statements must end with a semicolon) // Anything outside <?php tags is echoed automatically -?>Hello World Again! +?> +Hello World Again! <?php diff --git a/scala.html.markdown b/scala.html.markdown new file mode 100644 index 00000000..fef09404 --- /dev/null +++ b/scala.html.markdown @@ -0,0 +1,416 @@ +--- +language: Scala +filename: learnscala.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] +filename: learn.scala +--- + +Scala - the scalable language + +```cpp + +/* + Set yourself up: + + 1) Download Scala - http://www.scala-lang.org/downloads + 2) unzip/untar in your favourite location and put the bin subdir on the path + 3) Start a scala REPL by typing scala. You should see the prompt: + + scala> + + This is the so called REPL. You can run commands in the REPL. Let's do just + that: +*/ + +println(10) // prints the integer 10 + +println("Boo!") // printlns the string Boo! + + +// Some basics + +// Printing, and forcing a new line on the next print +println("Hello world!") +// Printing, without forcing a new line on next print +print("Hello world") + +// Declaring values is done using either var or val +// val declarations are immutable, whereas var's are mutable. Immutablility is +// a good thing. +val x = 10 // x is now 10 +x = 20 // error: reassignment to val +var x = 10 +x = 20 // x is now 20 + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Boolean values +true +false + +// Boolean operations +!true // false +!false // true +true == false // false +10 > 5 // true + +// Math is as per usual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + + +// Evaluating a command in the REPL gives you the type and value of the result + +1 + 7 + +/* The above line results in: + + scala> 1 + 7 + res29: Int = 8 + + This means the result of evaluating 1 + 7 is an object of type Int with a + value of 8 + + 1+7 will give you the same result +*/ + + +// Everything is an object, including a function. Type these in the REPL: + +7 // results in res30: Int = 7 (res30 is just a generated var name for the result) + +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x + +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x + +/* The above says this + + sq: Int => Int = <function1> + + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. + + sq can be executed as follows: +*/ + +sq(10) // Gives you this: res33: Int = 100. + +// Scala allows methods and functions to return, or take as parameters, other +// functions or methods. + +val add10: Int => Int = _ + 10 // A function taking an Int and returning an Int +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element + +// Anonymous functions can be used instead of named functions: +List(1, 2, 3) map (x => x + 10) + +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) + +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println + + + +// Data structures + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Throws an exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Why have this? +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // The function divideInts gives you the result and the remainder + +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element +val d = divideInts(10,3) + +d._1 + +d._2 + + + +// Combinators + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate +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 a foreach method defined on certain collections that takes a type +// returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + + + +// For comprehensions + +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 + +/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas + a for-comprehension defines a relationship between two sets of data. */ + + + +// Loops and iteration + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala is quite lenient when it comes to dots and brackets - study the +// rules separately. This helps write DSLs and APIs that read like English + +(5 to 1 by -1) foreach ( println ) + +// A while loops +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? + +i // Show the value of i. Note that while is a loop in the classical sense - + // it executes sequentially while changing the loop variable. while is very + // fast, faster that Java // loops, but using the combinators and + // comprehensions above is easier to understand and parallelize + +// A do while loop +do { + println("x is still less then 10"); + x += 1 +} while (x < 10) + +// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursive functions need an explicit return type, the compiler can't infer it. +// Here it's Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} + + + +// Conditionals + +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 } + + + +// Object oriented features + +// Classname is Dog +class Dog { + //A method called bark, returning a String + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// Classes can contain nearly any other construct, including other classes, +// functions, methods, objects, case classes, traits etc. + + + +// Case classes + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// Pattern matching + +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" } + + + +// Regular expressions + +val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// Strings + +"Scala strings are surrounded by double quotes" // +'a' // A Scala Char +'Single quote strings don't exist' // Error +"Strings have the usual Java methods defined on them".length +"They also have some extra Scala methods.".reverse + +// Seealso: 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") + +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" + +// Triple double-quotes let strings span multiple rows and contain quotes + +val html = """<form id="daform"> + <p>Press belo', Joe</p> + | <input type="submit"> + </form>""" + + + +// Application structure and organization + +// Importing things +import scala.collection.immutable.List + +// Import all "sub packages" +import scala.collection.immutable._ + +// Import multiple classes in one statement +import scala.collection.immutable.{List, Map} + +// Rename an import using '=>' +import scala.collection.immutable{ List => ImmutableList } + +// Import all classes, except some. The following excludes Map and Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Your programs entry point is defined in an scala file using an object, with a +// single method, main: +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// Files can contain multiple classes and objects. Compile with scalac + + + + +// Input and output + +// To read a file line by line +import scala.io.Source +for(line <- Source.fromPath("myfile.txt").getLines()) + println(line) + +// To write a file use Java's PrintWriter + + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school(http://twitter.github.io/scala_school/) + +[The scala documentation] + +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) + diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown new file mode 100755 index 00000000..8c24f0b8 --- /dev/null +++ b/zh-cn/git-cn.html.markdown @@ -0,0 +1,375 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: LearnGit.txt +lang: zh-cn +--- + +Git是一个分布式版本控制及源代码管理工具 + +Git可以为你的项目保存若干快照,以此来对整个项目进行版本管理 + +## 版本 + +### 什么是版本控制 + +版本控制系统就是根据时间来记录一个或多个文件的更改情况的系统。 + +### 集中式版本控制 VS 分布式版本控制 + +* 集中式版本控制的主要功能为同步,跟踪以及备份文件 +* 分布式版本控制则更注重共享更改。每一次更改都有唯一的标识 +* 分布式系统没有预定的结构。你也可以用git很轻松的实现SVN风格的集中式系统控制 + +[更多信息](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### 为什么要使用Git + +* 可以离线工作 +* 和他人协同工作变得简单 +* 分支很轻松 +* 合并很容易 +* Git系统速度快,也很灵活 + +## Git 架构 + + +### 版本库 + +一系列文件,目录,历史记录,提交记录和头指针。 +可以把它视作每个源代码文件都带有历史记录属性数据结构 + +一个Git版本库包括一个 .git 目录和其工作目录 + +### .git 目录(版本库的一部分) + +.git 目录包含所有的配置、日志、分支信息、头指针等 +[详细列表](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### 工作目录 (版本库的一部分) + +版本库中的目录和文件,可以看做就是你工作时的目录 + +### 索引(.git 目录) + +索引就是git中的 staging 区. 可以算作是把你的工作目录与Git版本库分割开的一层 +这使得开发者能够更灵活的决定要将要在版本库中添加什么内容 + +### 提交 + +一个 git 提交就是一组更改或者对工作目录操作的快照 +比如你添加了5个文件,删除了2个文件,那么这些变化就会被写入一个提交比如你添加了5个文件,删除了2个文件,那么这些变化就会被写入一个提交中 +而这个提交之后也可以被决定是否推送到另一个版本库中 + +### 分支 + +分支其实就是一个指向你最后一次的提交的指针 +当你提交时,这个指针就会自动指向最新的提交 + +### 头指针 与 头(.git 文件夹的作用) + +头指针是一个指向当前分支的指针,一个版本库只有一个当前活动的头指针 +而头则可以指向版本库中任意一个提交,每个版本库也可以有多个头 + +### 其他形象化解释 + +* [给计算机科学家的解释](http://eagain.net/articles/git-for-computer-scientists/) +* [给设计师的解释](http://hoth.entp.com/output/git_for_designers.html) + + +## 命令 + + +### 初始化 + +创建一个新的git版本库。这个版本库的配置、存储等信息会被保存到.git文件夹中 + +```bash +$ git init +``` + +### 配置 + +更改设置。可以是版本库的设置,也可以是系统的或全局的 + + +```bash +# 输出、设置基本的全局变量 +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[关于git的更多设置](http://git-scm.com/docs/git-config) + +### 帮助 + +git内置了对命令非常详细的解释,可以供我们快速查阅 + +```bash +# 查找可用命令 +$ git help + +# 查找所有可用命令 +$ git help -a + +# 在文档当中查找特定的命令 +# git help <命令> +$ git help add +$ git help commit +$ git help init +``` + +### 状态 + +显示索引文件(也就是当前工作空间)和当前的头指针指向的提交的不同 + + +```bash +# 显示分支,为跟踪文件,更改和其他不同 +$ git status + +# 查看其他的git status的用法 +$ git help status +``` + +### 添加 + +添加文件到当前工作空间中。如果你不使用 `git add` 将文件添加进去, +那么这些文件也不会添加到之后的提交之中 + +```bash +# 添加一个文件 +$ git add HelloWorld.java + +# 添加一个子目录中的文件 +$ git add /path/to/file/HelloWorld.c + +# 支持正则表达式 +$ git add ./*.java +``` + +### 分支 + +管理分支,可以通过下列命令对分支进行增删改查 + +```bash +# 查看所有的分支和远程分支 +$ git branch -a + +# 创建一个新的分支 +$ git branch myNewBranch + +# 删除一个分支 +$ git branch -d myBranch + +# 重命名分支 +# git branch -m <旧名称> <新名称> +$ git branch -m myBranchName myNewBranchName + +# 编辑分支的介绍 +$ git branch myBranchName --edit-description +``` + +### 检出 + +将当前工作空间更新到索引所标识的或者某一特定的工作空间 + +```bash +# 检出一个版本库,默认将更新到master分支 +$ git checkout +# 检出到一个特定的分支 +$ git checkout branchName +# 新建一个分支,并且切换过去,相当于"git branch <名字>; git checkout <名字>" +$ git checkout -b newBranch +``` + +### clone + +这个命令就是将一个版本库拷贝到另一个目录中,同时也将 +分支都拷贝到新的版本库中。这样就可以在新的版本库中提交到远程分支 + +```bash +# clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +将当前索引的更改保存为一个新的提交,这个提交包括用户做出的更改与信息 + +```bash +# 提交时附带提交信息 +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +显示当前工作空间和提交的不同 + +```bash +# 显示工作目录和索引的不同 +$ git diff + +# 显示索引和最近一次提交的不同 +$ git diff --cached + +# 显示宫缩目录和最近一次提交的不同 +$ git diff HEAD +``` + +### grep + +可以在版本库中快速查找 + +可选配置: + +```bash +# 感谢Travis Jeffery提供的以下用法: +# 在搜索结果中显示行号 +$ git config --global grep.lineNumber true + +# 是搜索结果可读性更好 +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# 在所有的java中查找variableName +$ git grep 'variableName' -- '*.java' + +# 搜索包含 "arrayListName" 和, "add" 或 "remove" 的所有行 +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +更多的例子可以查看: +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +显示这个版本库的所有提交 + +```bash +# 显示所有提交 +$ git log + +# 显示某几条提交信息 +$ git log -n 10 + +# 仅显示合并提交 +$ git log --merges +``` + +### merge + +合并就是将外部的提交合并到自己的分支中 + +```bash +# 将其他分支合并到当前分支 +$ git merge branchName + +# 在合并时创建一个新的合并后的提交 +$ git merge --no-ff branchName +``` + +### mv + +重命名或移动一个文件 + +```bash +# 重命名 +$ git mv HelloWorld.c HelloNewWorld.c + +# 移动 +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# 强制重命名或移动 +# 这个文件已经存在,将要覆盖掉 +$ git mv -f myFile existingFile +``` + +### pull + +从远端版本库合并到当前分支 + +```bash +# 从远端origin的master分支更新版本库 +# git pull <远端> <分支> +$ git pull origin master +``` + +### push + +把远端的版本库更新 + +```bash +# 把本地的分支更新到远端origin的master分支上 +# git push <远端> <分支> +# git push 相当于 git push origin master +$ git push origin master +``` + +### rebase (谨慎使用) + +将一个分支上所有的提交历史都应用到另一个分支上 +*不要在一个已经公开的远端分支上使用rebase*. + +```bash +# 将experimentBranch应用到master上面 +# git rebase <basebranch> <topicbranch> +$ git rebase master experimentBranch +``` + +[更多阅读](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (谨慎使用) + +将当前的头指针复位到一个特定的状态。这样可以使你撤销merge、pull、commits、add等 +这是个很强大的命令,但是在使用时一定要清楚其所产生的后果 + +```bash +# 使 staging 区域恢复到上次提交时的状态,不改变现在的工作目录 +$ git reset + +# 使 staging 区域恢复到上次提交时的状态,覆盖现在的工作目录 +$ git reset --hard + +# 将当前分支恢复到某次提交,不改变现在的工作目录 +# 在工作目录中所有的改变仍然存在 +$ git reset 31f2bb1 + +# 将当前分支恢复到某次提交,覆盖现在的工作目录 +# 并且删除所有未提交的改变和指定提交之后的所有提交 +$ git reset --hard 31f2bb1 +``` + +### rm + +和add相反,从工作空间中去掉某个文件爱你 + +```bash +# 移除 HelloWorld.c +$ git rm HelloWorld.c + +# 移除子目录中的文件 +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## 更多阅读 + +* [tryGit - 学习Git的有趣方式](http://try.github.io/levels/1/challenges/1) + +* [git-scm - 视频教程](http://git-scm.com/videos) + +* [git-scm - 文档](http://git-scm.com/docs) + +* [Atlassian Git - 教程与工作流程](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown new file mode 100755 index 00000000..cb0de467 --- /dev/null +++ b/zh-cn/haskell-cn.html.markdown @@ -0,0 +1,407 @@ +--- +language: haskell +filename: learn-haskell.hs +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Peiyong Lin", ""] +lang: zh-cn +--- + +Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads 及其类型系统而出名,但是我回归到它本身因为。Haskell 使得编程对于我而言是一种真正的快乐。 + +```haskell +-- 单行注释以两个破折号开头 +{- 多行注释像这样 + 被一个闭合的块包围 +-} + +---------------------------------------------------- +-- 1. 简单的数据类型和操作符 +---------------------------------------------------- + +-- 你有数字 +3 -- 3 +-- 数学计算就像你所期待的那样 +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- 默认除法不是整除 +35 / 4 -- 8.75 + +-- 整除 +35 `div` 4 -- 8 + +-- 布尔值也简单 +True +False + +-- 布尔操作 +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- 在上述的例子中,`not` 是一个接受一个值的函数。 +-- Haskell 不需要括号来调用函数。。。所有的参数 +-- 都只是在函数名之后列出来。因此,通常的函数调用模式是: +-- func arg1 arg2 arg3... +-- 查看关于函数的章节以获得如何写你自己的函数的相关信息。 + +-- 字符串和字符 +"This is a string." +'a' -- 字符 +'对于字符串你不能使用单引号。' -- 错误! + +-- 连结字符串 +"Hello " ++ "world!" -- "Hello world!" + +-- 一个字符串是一系列字符 +"This is a string" !! 0 -- 'T' + + +---------------------------------------------------- +-- 列表和元组 +---------------------------------------------------- + +-- 一个列表中的每一个元素都必须是相同的类型 +-- 下面两个列表一样 +[1, 2, 3, 4, 5] +[1..5] + +-- 在 Haskell 你可以拥有含有无限元素的列表 +[1..] -- 一个含有所有自然数的列表 + +-- 因为 Haskell 有“懒惰计算”,所以无限元素的列表可以正常运作。这意味着 +-- Haskell 可以只在它需要的时候计算。所以你可以请求 +-- 列表中的第1000个元素,Haskell 会返回给你 + +[1..] !! 999 -- 1000 + +-- Haskell 计算了列表中 1 - 1000 个元素。。。但是 +-- 这个无限元素的列表中剩下的元素还不存在! Haskell 不会 +-- 真正地计算它们知道它需要。 + +<FS>- 连接两个列表 +[1..5] ++ [6..10] + +-- 往列表头增加元素 +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- 列表中的下标 +[0..] !! 5 -- 5 + +-- 更多列表操作 +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- 列表推导 +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- 附带条件 +[x*2 | x <-[1..5], x*2 > 4] -- [6, 8, 10] + +-- 元组中的每一个元素可以是不同类型的,但是一个元组 +-- 的长度是固定的 +-- 一个元组 +("haskell", 1) + +-- 获取元组中的元素 +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. 函数 +---------------------------------------------------- +-- 一个接受两个变量的简单函数 +add a b = a + b + +-- 注意,如果你使用 ghci (Hakell 解释器) +-- 你将需要使用 `let`,也就是 +-- let add a b = a + b + +-- 使用函数 +add 1 2 -- 3 + +-- 你也可以把函数放置在两个参数之间 +-- 附带倒引号: +1 `add` 2 -- 3 + +-- 你也可以定义不带字符的函数!这使得 +-- 你定义自己的操作符!这里有一个操作符 +-- 来做整除 +(//) a b = a `div` b +35 // 4 -- 8 + +-- 守卫:一个简单的方法在函数里做分支 +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- 模式匹配是类型的。这里有三种不同的 fib +-- 定义。Haskell 将自动调用第一个 +-- 匹配值的模式的函数。 +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- 元组的模式匹配: +foo (x, y) = (x + 1, y + 2) + +-- 列表的模式匹配。这里 `x` 是列表中第一个元素, +-- 并且 `xs` 是列表剩余的部分。我们可以写 +-- 自己的 map 函数: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- 编写出来的匿名函数带有一个反斜杠,后面跟着 +-- 所有的参数。 +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- 使用 fold (在一些语言称为`inject`)随着一个匿名的 +-- 函数。foldl1 意味着左折叠(fold left), 并且使用列表中第一个值 +-- 作为累加器的初始化值。 +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. 更多的函数 +---------------------------------------------------- + +-- 柯里化(currying):如果你不传递函数中所有的参数, +-- 它就变成“柯里化的”。这意味着,它返回一个接受剩余参数的函数。 + +add a b = a + b +foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 +foo 5 -- 15 + +-- 另外一种方式去做同样的事 +foo = (+10) +foo 5 -- 15 + +-- 函数组合 +-- (.) 函数把其它函数链接到一起 +-- 举个列子,这里 foo 是一个接受一个值的函数。它对接受的值加 10, +-- 并对结果乘以 5,之后返回最后的值。 +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- 修复优先级 +-- Haskell 有另外一个函数称为 `$`。它改变优先级 +-- 使得其左侧的每一个操作先计算然后应用到 +-- 右侧的每一个操作。你可以使用 `.` 和 `$` 来除去很多 +-- 括号: + +-- before +(even (fib 7)) -- true + +-- after +even . fib $ 7 -- true + +---------------------------------------------------- +-- 5. 类型签名 +---------------------------------------------------- + +-- Haskell 有一个非常强壮的类型系统,一切都有一个类型签名。 + +-- 一些基本的类型: +5 :: Integer +"hello" :: String +True :: Bool + +-- 函数也有类型。 +-- `not` 接受一个布尔型返回一个布尔型: +-- not :: Bool -> Bool + +-- 这是接受两个参数的函数: +-- add :: Integer -> Integer -> Integer + +-- 当你定义一个值,在其上写明它的类型是一个好实践: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. 控制流和 If 语句 +---------------------------------------------------- + +-- if 语句 +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- if 语句也可以有多行,缩进是很重要的 +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case 语句:这里是你可以怎样去解析命令行参数 +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell 没有循环因为它使用递归取代之。 +-- map 应用一个函数到一个数组中的每一个元素 + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- 你可以使用 map 来编写 for 函数 +for array func = map func array + +-- 然后使用它 +for [0..5] $ \i -> show i + +-- 我们也可以像这样写: +for [0..5] show + +-- 你可以使用 foldl 或者 foldr 来分解列表 +-- foldl <fn> <initial value> <list> +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- 这和下面是一样的 +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl 是左手边的,foldr 是右手边的- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- 这和下面是一样的 +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. 数据类型 +---------------------------------------------------- + +-- 这里展示在 Haskell 中你怎样编写自己的数据类型 + +data Color = Red | Blue | Green + +-- 现在你可以在函数中使用它: + + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" + +-- 你的数据类型也可以有参数: + +data Maybe a = Nothing | Just a + +-- 类型 Maybe 的所有 +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- 虽然在没有解释 monads 的情况下 IO不能被完全地解释, +-- 着手解释到位并不难。 + +-- 当一个 Haskell 程序被执行,函数 `main` 就被调用。 +-- 它必须返回一个类型 `IO ()` 的值。举个列子: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () + +-- 如果你能实现你的程序依照函数从 String 到 String,那样编写 IO 是最简单的。 +-- 函数 +-- interact :: (String -> String) -> IO () +-- 输入一些文本,在其上运行一个函数,并打印出输出 + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- 你可以考虑一个 `IO()` 类型的值,当做一系列计算机所完成的动作的代表, +-- 就像一个以命令式语言编写的计算机程序。我们可以使用 `do` 符号来把动作链接到一起。 +-- 举个列子: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- this gets a line and gives it the name "input" + putStrLn $ "Hello, " ++ name + +-- 练习:编写只读取一行输入的 `interact` + +-- 然而,`sayHello` 中的代码将不会被执行。唯一被执行的动作是 `main` 的值。 +-- 为了运行 `sayHello`,注释上面 `main` 的定义,并代替它: +-- main = sayHello + +-- 让我们来更好地理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: +-- getLine :: IO String +-- 你可以考虑一个 `IO a` 类型的值,代表一个当被执行的时候 +-- 将产生一个 `a` 类型的值的计算机程序(除了它所做的任何事之外)。我们可以保存和重用这个值通过 `<-`。 +-- 我们也可以写自己的 `IO String` 类型的动作: + +action :: IO String +action = do + putStrLn "This is a line. Duh" + input1 <- getLine + input2 <- getLine + -- The type of the `do` statement is that of its last line. + -- `return` is not a keyword, but merely a function + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- 我们可以使用这个动作就像我们使用 `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- `IO` 类型是一个 "monad" 的例子。Haskell 使用一个 monad 来做 IO的方式允许它是一门纯函数式语言。 +-- 任何与外界交互的函数(也就是 IO) 都在它的类型签名处做一个 `IO` 标志 +-- 着让我们推出 什么样的函数是“纯洁的”(不与外界交互,不修改状态) 和 什么样的函数不是 “纯洁的” + +-- 这是一个强有力的特征,因为并发地运行纯函数是简单的;因此,Haskell 中并发是非常简单的。 + + +---------------------------------------------------- +-- 9. The Haskell REPL +---------------------------------------------------- + +-- 键入 `ghci` 开始 repl。 +-- 现在你可以键入 Haskell 代码。 +-- 任何新值都需要通过 `let` 来创建: + +let foo = 5 + +-- 你可以查看任何值的类型,通过命令 `:t`: + +>:t foo +foo :: Integer + +-- 你也可以运行任何 `IO ()`类型的动作 + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +还有很多关于 Haskell,包括类型类和 monads。这些是使得编码 Haskell 是如此有趣的主意。我用一个最后的 Haskell 例子来结束:一个 Haskell 的快排实现: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +安装 Haskell 是简单的。你可以从[这里](http://www.haskell.org/platform/)获得它。 + +你可以从优秀的 +[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/javascript.html.markdown b/zh-cn/javascript-cn.html.markdown index 3b5cfa94..3b5cfa94 100755 --- a/zh-cn/javascript.html.markdown +++ b/zh-cn/javascript-cn.html.markdown diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown new file mode 100755 index 00000000..259e4ed8 --- /dev/null +++ b/zh-cn/python-cn.html.markdown @@ -0,0 +1,475 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: learnpython.py +lang: zh-cn +--- + +Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一 +我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码 + +很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我 + +注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本 +如果是Python 3,请在网络上寻找其他教程 + +```python +# 单行注释 +""" 多行字符串可以用 + 三个引号包裹,不过这也可以被当做 + 多行注释 +""" + +#################################################### +## 1. 原始数据类型和操作符 +#################################################### + +# 数字类型 +3 #=> 3 + +# 简单的算数 +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 整数的除法会自动取整 +5 / 2 #=> 2 + +# 要做精确的除法,我们需要引入浮点数 +2.0 # 浮点数 +11.0 / 4.0 #=> 2.75 好多了 + +# 括号具有最高优先级 +(1 + 3) * 2 #=> 8 + +# 布尔值也是原始数据类型 +True +False + +# 用not来取非 +not True #=> False +not False #=> True + +# 相等 +1 == 1 #=> True +2 == 1 #=> False + +# 不等 +1 != 1 #=> False +2 != 1 #=> True + +# 更多的比较操作符 +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# 比较运算可以连起来写! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# 字符串通过"或'括起来 +"This is a string." +'This is also a string.' + +# 字符串通过加号拼接 +"Hello " + "world!" #=> "Hello world!" + +# 字符串可以被视为字符的列表 +"This is a string"[0] #=> 'T' + +# % 可以用来格式化字符串 +"%s can be %s" % ("strings", "interpolated") + +# 也可以用format方法来格式化字符串 +# 推荐使用这个方法 +"{0} can be {1}".format("strings", "formatted") +# 也可以用变量名代替数字 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None 是对象 +None #=> None + +# 不要用相等 `==` 符号来和None进行比较 +# 要用 `is` +"etc" is None #=> False +None is None #=> True + +# 'is' 可以用来比较对象的相等性 +# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 + +# None, 0, 和空字符串都被算作False +# 其他的均为True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. 变量和集合 +#################################################### + +# 很方便的输出 +print "I'm Python. Nice to meet you!" + + +# 给变量赋值前不需要事先生命 +some_var = 5 # 规范用小写字母和下划线来做为变量名 +some_var #=> 5 + +# 访问之前为赋值的变量会抛出异常 +# 查看控制流程一节来了解异常处理 +some_other_var # 抛出命名异常 + +# if语句可以作为表达式来使用 +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# 列表用来保存序列 +li = [] +# 可以直接初始化列表 +other_li = [4, 5, 6] + +# 在列表末尾添加元素 +li.append(1) #li 现在是 [1] +li.append(2) #li 现在是 [1, 2] +li.append(4) #li 现在是 [1, 2, 4] +li.append(3) #li 现在是 [1, 2, 4, 3] +# 移除列表末尾元素 +li.pop() #=> 3 and li is now [1, 2, 4] +# 放回来 +li.append(3) # li is now [1, 2, 4, 3] again. + +# 像其他语言访问数组一样访问列表 +li[0] #=> 1 +# 访问最后一个元素 +li[-1] #=> 3 + +# 越界会抛出异常 +li[4] # 抛出越界异常 + +# 切片语法需要用到列表的索引访问 +# 可以看做数学之中左闭右开区间 +li[1:3] #=> [2, 4] +# 省略开头的元素 +li[2:] #=> [4, 3] +# 省略末尾的元素 +li[:3] #=> [1, 2, 4] + +# 删除特定元素 +del li[2] # li 现在是 [1, 2, 3] + +# 合并列表 +li + other_li #=> [1, 2, 3, 4, 5, 6] - 不改变这两个列表 + +# 通过拼接合并列表 +li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] + +# 用in来返回元素是否在列表中 +1 in li #=> True + +# 返回列表长度 +len(li) #=> 6 + + +# 元组类似于列表,但是他是不可改变的 +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # 类型错误 + +# 对于大多数的列表操作,也适用于元组 +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# 你可以将元组解包赋给多个变量 +a, b, c = (1, 2, 3) # a是1,b是2,c是3 +# 如果不加括号,那么会自动视为元组 +d, e, f = 4, 5, 6 +# 现在我们可以看看交换两个数字是多么容易的事 +e, d = d, e # d是5,e是4 + + +# 字典用来储存映射关系 +empty_dict = {} +# 字典初始化 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 字典也用中括号访问元素 +filled_dict["one"] #=> 1 + +# 把所有的键保存在列表中 +filled_dict.keys() #=> ["three", "two", "one"] +# 键的顺序并不是唯一的,得到的不一定是这个顺序 + +# 把所有的值保存在列表中 +filled_dict.values() #=> [3, 2, 1] +# 和键的顺序相同 + +# 判断一个键是否存在 +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# 查询一个不存在的键会抛出键异常 +filled_dict["four"] # 键异常 + +# 用get方法来避免键异常 +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get方法支持在不存在的时候返回一个默认值 +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Setdefault是一个更安全的添加字典元素的方法 +filled_dict.setdefault("five", 5) #filled_dict["five"] 的值为 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] 的值仍然是 5 + + +# 集合储存无顺序的元素 +empty_set = set() +# 出事话一个集合 +some_set = set([1,2,2,3,4]) # filled_set 现在是 set([1, 2, 3, 4]) + +# Python 2.7 之后,大括号可以用来表示集合 +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# 为集合添加元素 +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} + +# 用&来实现集合的交 +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# 用|来实现集合的并 +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# 用-来实现集合的差 +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# 用in来判断元素是否存在于集合中 +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. 控制流程 +#################################################### + +# 新建一个变量 +some_var = 5 + +# 这是个if语句,在python中缩进是很重要的。 +# 会输出 "some var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # 这个 elif 语句是不必须的 + print "some_var is smaller than 10." +else: # 也不是必须的 + print "some_var is indeed 10." + + +""" +用for循环遍历列表 +输出: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # 你可以用 % 来格式化字符串 + print "%s is a mammal" % animal + +""" +`range(number)` 返回从0到给定数字的列表 +输出: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While循环 +输出: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# 用 try/except块来处理异常 + +# Python 2.6 及以上适用: +try: + # 用raise来抛出异常 + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass就是什么都不做,不过通常这里会做一些恢复工作 + + +#################################################### +## 4. 函数 +#################################################### + +# 用def来新建函数 +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# 调用带参数的函数 +add(5, 6) #=> 输出 "x is 5 and y is 6" 返回 11 + +# 通过关键字赋值来调用函数 +add(y=6, x=5) # 顺序是无所谓的 + +# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的 +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 +def keyword_args(**kwargs): + return kwargs + +# 实际效果: +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# 你也可以同时将一个函数定义成两种形式 +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 当调用函数的时候,我们也可以和之前所做的相反,把元组和字典展开为参数 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + +# Python 有一等函数: +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# 匿名函数 +(lambda x: x > 2)(3) #=> True + +# 内置高阶函数 +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# 可以用列表方法来对高阶函数进行更巧妙的引用 +[add_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. 类 +#################################################### + +# 我们新建的类是从object类中继承的 +class Human(object): + + # 类属性,由所有类的对象共享 + species = "H. sapiens" + + # 基本构造函数 + def __init__(self, name): + # 将参数赋给对象成员属性 + self.name = name + + # 成员方法,参数要有self + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # 类方法由所有类的对象共享 + # 这类方法在调用时,会把类本身传给第一个参数 + @classmethod + def get_species(cls): + return cls.species + + # 静态方法是不需要类和对象的引用就可以调用的方法 + @staticmethod + def grunt(): + return "*grunt*" + + +# 实例化一个类 +i = Human(name="Ian") +print i.say("hi") # 输出 "Ian: hi" + +j = Human("Joel") +print j.say("hello") # 输出 "Joel: hello" + +# 访问类的方法 +i.get_species() #=> "H. sapiens" + +# 改变共享属性 +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# 访问静态变量 +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. 模块 +#################################################### + +# 我们可以导入其他模块 +import math +print math.sqrt(16) #=> 4 + +# 我们也可以从一个模块中特定的函数 +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# 从模块中导入所有的函数 +# 警告:不推荐使用 +from math import * + +# 简写模块名 +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python的模块其实只是普通的python文件 +# 你也可以创建自己的模块,并且导入它们 +# 模块的名字就和文件的名字相同 + +# 以可以通过下面的信息找找要成为模块需要什么属性或方法 +import math +dir(math) + + +``` + +## 更多阅读 + +希望学到更多?试试下面的链接: + +* [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/) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown new file mode 100644 index 00000000..f66d1a03 --- /dev/null +++ b/zh-cn/ruby-cn.html.markdown @@ -0,0 +1,329 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] +translators: + - ["Lin Xiangyu", "https://github.com/oa414"] +--- + +```ruby +# 这是单行注释 + +=begin +这是多行注释 +没人用这个 +你也不该用 +=end + +# 首先,也是最重要的,所有东西都是对象 + +# 数字是对象 + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# 一些基本的算术符号 +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 算术符号只是语法糖而已 +# 实际上是调用对象的方法 +1.+(3) #=> 4 +10.* 5 #=> 50 + +# 特殊的只也是对象 +nil # 空 +true # 真 +false # 假 + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# 相等运算符 +1 == 1 #=> true +2 == 1 #=> false + +# 不等运算符 +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# 除了false自己,nil是唯一的值为false的对象 + +!nil #=> true +!false #=> true +!0 #=> false + +# 更多比较 +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# 字符串是对象 + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = "use string interpolation" +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + + +# 输出值 +puts "I'm printing!" + +# 变量 +x = 25 #=> 25 +x #=> 25 + +# 注意赋值语句返回了赋的值 +# 这意味着你可以用多重赋值语句 + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# 按照惯例,用snake_case 作为变量名 +snake_case = true + +# 使用具有描述性的运算符 +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# 符号(Symbols,也是对象) +# 符号是不可变的,内部用整数类型表示的可重用的值。通常用它代替字符串来有效地表达有意义的值 + + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# 数组 + +# 这是一个数组 +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# 数组可以包含不同类型的元素 + +array = [1, "hello", false] #=> => [1, "hello", false] + +# 数组可以被索引 +# 从前面开始 +array[0] #=> 1 +array[12] #=> nil + +# 像运算符一样,[var]形式的访问 +# 也就是一个语法糖 +# 实际上是调用对象的[] 方法 +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# 从尾部开始 +array[-1] #=> 5 + +# 同时指定开始的位置和结束的位置 +array[2, 4] #=> [3, 4, 5] + +# 或者指定一个范围 +array[1..3] #=> [2, 3, 4] + +# 像这样往数组增加一个元素 +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# 哈希表是Ruby的键值对的基本数据结构 +# 哈希表由大括号定义 +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# 哈希表可以通过键快速地查询 +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# 查询一个不存在地键将会返回nil +hash['nothing here'] #=> nil + +# 用 #each 方法来枚举哈希表: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +# 从Ruby 1.9开始, 用符号作为键的时候有特别的记号表示: + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# 小贴士:数组和哈希表都是可枚举的 +# 它们可以共享一些有用的方法,比如each, map, count, 和more + +# 控制流 + +if true + "if statement" +elsif false + "else if, optional" +else + "else, also optional" +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# 然而 +# 没人用for循环 +# 用`each`来代替,就像这样 + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts "Way to go kiddo" +when 'B' + puts "Better luck next time" +when 'C' + puts "You can do better" +when 'D' + puts "Scraping through" +when 'F' + puts "You failed!" +else + puts "Alternative grading system, eh?" +end + +# 函数 + +def double(x) + x * 2 +end + +# 函数 (以及所有的方法块) 隐式地返回了最后语句的值 +double(2) #=> 4 + +# 当不存在歧义的时候括号是可有可无的 +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# 方法的参数通过逗号分隔 +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# 所有的方法都有一个隐式的块参数 +# 可以用yield参数调用 + +def surround + puts "{" + yield + puts "}" +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# 用class关键字定义一个类 +class Human + + # 一个类变量,它被这个类地所有实例变量共享 + @@species = "H. sapiens" + + # 构造函数 + def initialize(name, age=0) + # 将参数name的值赋给实例变量@name + @name = name + # 如果没有给出age, 那么会采用参数列表中地默认地值 + @age = age + end + + # 基本的 setter 方法 + def name=(name) + @name = name + end + + # 基本地 getter 方法 + def name + @name + end + + # 一个类方法以self.开头 + # 它可以被类调用,但不能被类的实例调用 + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# 类的例子 +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# 让我们来调用一些方法 +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# 调用对象的方法 +Human.say("Hi") #=> "Hi" + +``` |