您好,登錄后才能下訂單哦!
本篇內容主要講解“Ruby語言實例代碼分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Ruby語言實例代碼分析”吧!
# This is a comment # 這是一行注釋 =begin This is a multiline comment No-one uses them You 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 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 # Arithmetic is just syntactic sugar # for calling a method on an object # 這些運算符實際上都是語法糖, # 相當于在對象上調用方法 1.+(3) #=> 4 10.* 5 #=> 50 # Special values are objects # 特殊值也是對象 nil # Nothing to see here # 空值 true # truth # 真值 false # falsehood # 假值 nil.class #=> NilClass true.class #=> TrueClass false.class #=> FalseClass # Equality # 等式判斷 1 == 1 #=> true 2 == 1 #=> false # Inequality # 不等式判斷 1 != 1 #=> false 2 != 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 #=> true 1 > 10 #=> false 2 <= 2 #=> true 2 >= 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 #=> 25 x #=> 25 # Note that assignment returns the value assigned # This means you can do multiple assignment: # 請注意,賦值語句會返回被賦進變量的那個值, # 這意味著你可以進行多重賦值: x = y = 10 #=> 10 x #=> 10 y #=> 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 #=> Symbol status = :pending status == :pending #=> true status == 'pending' #=> false status == :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] #=> 1 array[12] #=> nil # Like arithmetic, [var] access # is just syntactic sugar # for calling a method [] on an object # 類似于運算符,[var] 這種查詢語法也是語法糖, # 相當于在對象上調用 [] 方法 array.[] 0 #=> 1 array.[] 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 語句) end for 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 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 # Functions # 函數 def double(x) x * 2 end # 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 #=> 6 double double 3 #=> 12 # (譯注:連續省略小括號居然也可以!) def sum(x,y) x + y end # Method arguments are separated by a comma # 方法的參數使用逗號來分隔 sum 3, 4 #=> 7 sum 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 "}" end surround { 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 end end # 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"
到此,相信大家對“Ruby語言實例代碼分析”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。