「譯」 分分鐘學會一門語言之 Ruby 篇

宣告:原文版權屬於 David Underwood、Joel Walden 和 Luke Holder,原文以 CC BY-SA 3。0 協議釋出。

# This is a comment# 這是一行註釋=beginThis is a multiline commentNo-one uses themYou shouldn‘t either多行註釋是這樣寫的,沒人用它,你也不要用它。=end# First and foremost: Everything is an object。# 第一條也是最重要的一條:每樣東西都是物件。# Numbers are objects# 數字是物件3。class #=> Fixnum # (譯註:`class` 屬性指向物件所屬的類。這裡的 Fixnum 即整數類。)3。to_s #=> “3” # (譯註:`to_s` 是整數物件的一個方法,其作用是轉換為字串。)# Some basic arithmetic# 一些基本運算1 + 1 #=> 28 - 1 #=> 710 * 2 #=> 2035 / 5 #=> 7# Arithmetic is just syntactic sugar# for calling a method on an object# 這些運算子實際上都是語法糖,# 相當於在物件上呼叫方法1。+(3) #=> 410。* 5 #=> 50# Special values are objects# 特殊值也是物件nil # Nothing to see here # 空值true # truth # 真值false # falsehood # 假值nil。class #=> NilClasstrue。class #=> TrueClassfalse。class #=> FalseClass# Equality# 等式判斷1 == 1 #=> true2 == 1 #=> false# Inequality# 不等式判斷1 != 1 #=> false2 != 1 #=> true!true #=> false!false #=> true# apart from false itself, nil is the only other ’falsey‘ value# 除了 false 本身之外,nil 是剩下的唯一假值!nil #=> true!false #=> true!0 #=> false # (譯註:這個毀三觀啊!)# More comparisons# 更多比較操作1 < 10 #=> true1 > 10 #=> false2 <= 2 #=> true2 >= 2 #=> true# Strings are objects# 字串當然還是物件’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”# (譯註:這裡展現了字串插入方法。)# print to the output# 列印輸出puts “I’m printing!”# Variables# 變數x = 25 #=> 25x #=> 25# Note that assignment returns the value assigned# This means you can do multiple assignment:# 請注意,賦值語句會返回被賦進變數的那個值,# 這意味著你可以進行多重賦值:x = y = 10 #=> 10x #=> 10y #=> 10# By convention, use snake_case for variable names# 按照慣例,變數名使用由下劃線串連的小寫字母# (譯註:因為看起來像一條蛇,這種拼寫稱作“snake case”)snake_case = true# Use descriptive variable names# 建議使用描述性的變數名path_to_project_root = ‘/good/name/’path = ‘/bad/name/’# Symbols (are objects)# Symbols are immutable, reusable constants represented internally by an# integer value。 They‘re often used instead of strings to efficiently convey# specific, meaningful values# 符號(也是物件)# 符號是不可修改的、可重用的常量,在內部表示為一個整數值。# 它們通常被用來代替字串,來有效地傳遞一些特定的、有意義的值。:pending。class #=> Symbolstatus = :pendingstatus == :pending #=> truestatus == ’pending‘ #=> falsestatus == :approved #=> false# Arrays# 陣列# This is an array# 這是一個數組[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]# Arrays can contain different types of items# 陣列可以包含不同型別的元素array = [1, “hello”, false] #=> => [1, “hello”, false]# Arrays can be indexed# From the front# 陣列可以用索引號來查詢,下面是順序索引查詢array[0] #=> 1array[12] #=> nil# Like arithmetic, [var] access# is just syntactic sugar# for calling a method [] on an object# 類似於運算子,[var] 這種查詢語法也是語法糖,# 相當於在物件上呼叫 [] 方法array。[] 0 #=> 1array。[] 12 #=> nil# From the end# 下面是逆向索引查詢array[-1] #=> 5# With a start and end index# 使用開始和結束索引來查詢array[2, 4] #=> [3, 4, 5]# Or with a range# 或者使用範圍來查詢array[1。。3] #=> [2, 3, 4]# Add to an array like this# 用這種方式來向陣列追加元素array << 6 #=> [1, 2, 3, 4, 5, 6]# Hashes are Ruby’s primary dictionary with keys/value pairs。# Hashes are denoted with curly braces:# 雜湊表是 Ruby 最主要的字典型名值對資料。# 雜湊表用花括號來表示:hash = {‘color’ => ‘green’, ‘number’ => 5}hash。keys #=> [‘color’, ‘number’]# Hashes can be quickly looked up by key:# 雜湊表可以透過鍵名來快速查詢:hash[‘color’] #=> ‘green’hash[‘number’] #=> 5# Asking a hash for a key that doesn‘t exist returns nil:# 向雜湊表查詢一個不存在的鍵名會返回 nil:hash[’nothing here‘] #=> nil# Iterate over hashes with the #each method:# 使用 #each 方法來迭代雜湊表:hash。each do |k, v| puts “#{k} is #{v}”end# Since Ruby 1。9, there’s a special syntax when using symbols as keys:# 從 Ruby 1。9 開始,當使用符號作為鍵名時,有其特定語法:new_hash = { defcon: 3, action: true}new_hash。keys #=> [:defcon, :action]# Tip: Both Arrays and Hashes are Enumerable# They share a lot of useful methods such as each, map, count, and more# 提示:陣列和雜湊表都是可列舉的。# 它們擁有很多相似的方法,比如 each、map、count 等等。# Control structures# 控制結構if true “if statement” # (譯註:條件語句)elsif false “else if, optional” # (譯註:可選的 else if 語句)else “else, also optional” # (譯註:同樣也是可選的 else 語句)endfor counter in 1。。5 puts “iteration #{counter}”end#=> iteration 1#=> iteration 2#=> iteration 3#=> iteration 4#=> iteration 5# HOWEVER# No-one uses for loops# Use `each` instead, like this:# 不過,# 沒人喜歡用 for 迴圈,# 大家都用 `each` 來代替了,像這樣:(1。。5)。each do |counter| puts “iteration #{counter}”end#=> iteration 1#=> iteration 2#=> iteration 3#=> iteration 4#=> iteration 5counter = 1while counter <= 5 do puts “iteration #{counter}” counter += 1end#=> iteration 1#=> iteration 2#=> iteration 3#=> iteration 4#=> iteration 5grade = ‘B’case gradewhen ‘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# Functions# 函式def double(x) x * 2end# Functions (and all blocks) implcitly return the value of the last statement# 函式(包括所有的程式碼塊)隱式地返回最後一行語句的值double(2) #=> 4# Parentheses are optional where the result is unambiguous# 當不會產生歧義時,小括號居然也是可寫可不寫的。double 3 #=> 6double double 3 #=> 12# (譯註:連續省略小括號居然也可以!)def sum(x,y) x + yend# Method arguments are separated by a comma# 方法的引數使用逗號來分隔sum 3, 4 #=> 7sum sum(3,4), 5 #=> 12# yield# All methods have an implicit, optional block parameter# it can be called with the ‘yield’ keyword# 所有的方法都有一個隱式的、可選的塊級引數,# 它可以透過 `yield` 關鍵字來呼叫。def surround puts “{” yield puts “}”endsurround { puts ‘hello world’ }# {# hello world# }# Define a class with the class keyword# 使用 class 關鍵字來定義類class Human # A class variable。 It is shared by all instances of this class。 # 一個類變數。它將被這個類的所有例項所共享。 @@species = “H。 sapiens” # Basic initializer # 基本的初始化函式(建構函式) def initialize(name, age=0) # Assign the argument to the “name” instance variable for the instance # 把引數 `name` 賦值給例項變數 `@name` @name = name # If no age given, we will fall back to the default in the arguments list。 # 如果沒有指定 age,我們會從引數列表中獲取後備的預設值。 @age = age end # Basic setter method # 基本的 setter 方法 def name=(name) @name = name end # Basic getter method # 基本的 getter 方法 def name @name end # A class method uses self to distinguish from instance methods。 # It can only be called on the class, not an instance。 # 一個類方法使用開頭的 `self` 來與例項方法區分開來。 # 它只能在類上呼叫,而無法在例項上呼叫。 def self。say(msg) puts “#{msg}” end def species @@species endend# Instantiate a class# 例項化一個類jim = Human。new(“Jim Halpert”)dwight = Human。new(“Dwight K。 Schrute”)# Let‘s call a couple of methods# 我們試著呼叫一些方法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”# Call the class method# 呼叫類方法Human。say(“Hi”) #=> “Hi”

希望本文能幫助到您!

點贊+轉發,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓-_-)

關注 {我},享受文章首發體驗!

每週重點攻克一個前端技術難點。更多精彩前端內容私信 我 回覆“教程”

原文連結:https://github。com/cssmagic/blog/issues/26

「譯」 分分鐘學會一門語言之 Ruby 篇