ruby 快速學習

說明:
1. [xxx] 表示語法可省略
2. (物件導向) 所有的函數調用,都是用 “.” 來調用,不會出現 python或JS類的 parseInt(n)/int(n) 這樣的寫法,只有 n.to_s

基礎

中文問題

遇到中文: 必須在首行添加下面代碼

# -*- coding: UTF-8 -*- # 必須在首行

註釋問題

# -*- coding: UTF-8 -*- # 必須在首行
# 這是單行註釋

=begin
這是多行註釋;
這是多行註釋;
=end

定義函數

define xxx
 ...
end

輸出

puts: 可換行

print: 單行輸出不換行,多行輸出作爲字符串塊

echo: (執行函數)

puts 'xxx'

空白問題

a + b 被解釋爲 a+b (這是一個局部變量)
a +b 被解釋爲 a(+b) (這是一個方法調用)

保留關鍵字

BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return while
def in self FILE
defined? module super LINE

字符串的集中表達方式

# -*- coding: UTF-8 -*-
print <<EOF 
    aa
    bb
EOF
print '---'  #不會換行
print <<'EOF'
    aa
    bb
EOF
puts '執行命令'
print <<`hehe` # 此處要注意,必須有一個 "<<"
    echo 你好  #  ``該執行符號 得 配合 echo  一起使用
hehe

puts '多個命令'
print <<hehe,<<haha  #該處的"<<"後不能有空格,變量緊跟"<<"
    呵呵   
hehe
    哈哈
haha

程序執行前後操作

BEGIN 和 END 屬於塊級函數,一個程序可有多個塊級程序

BEGIN 程序在程序運行前調用,即初始化程序;

BEGIN {
    puts 'want to do,starting...'
}

END 程序在程序退出前調用

END{
    puts 'want to do,ending...'
}

引號問題

和其他語言一樣,單雙引號互用

變量在字符串內的展示

name = 'ruby'
puts name
puts "this is #{name}" # 着重:此處必須雙引號,否則不能解析變量

數組及遍歷

1.數組遍歷

#第一種
arr = [ "fred", 10, 3.14, "This is a string", "last element", ]
arr.each do |i|
    puts i 
end
# 第二種
(5..9).each do |d|
    puts d,'--->'
end

輸出數組

arr = Array.new(10)
puts "#{arr}"

2.新建數組

# -*- coding: UTF-8 -*- # 必須在首行

#new()
arr = Array.new(20)
puts "#{arr}" 
=begin
特別奇怪??? 爲什麼輸出的是 ['nil',...]????
難道是建立一個空的數組位置,但沒有賦值
=end

#範圍內創建數組
(5..9).each do {|d| puts "#{d}"}
arr = Array(5...9)
puts arr.size
puts "#{arr}"
#.[]()
arr = Array.[](1,2,3,4)  #有點函數
#[]
arr = Array[1,2,3,4]    #直接賦值
#每個元素賦同樣的值
arr = Array.new(4,'都一樣') 
puts "#{arr}"
#lambda 表達式
arr = Array.new(10){|e| e = e*2}
puts arr.size

3.數組屬性

arr = Array.new(20)

puts arr.size
puts arr.length

索引數組值

arr = Array(5,9);
puts "#{arra.at(6)}"

類型轉換

string 類型轉換

a = '1'
a.to_s  # 字符串
a.to_f  # 浮點型
a.to_i  # 整數

字串符號Symbols

Symbol是唯一且不會變動的識別名稱,用冒號開頭:

:this_is_a_symbol
爲什麼不就用字串呢?這是因爲相同名稱的Symbol不會再重複建構物件,所以使用Symbol可以執行的更有效率。範例如下:

puts "foobar".object_id      # 輸出 2151854740
puts "foobar".object_id      # 輸出 2151830100
puts :foobar.object_id       # 輸出 577768
puts :foobar.object_id       # 輸出 577768

類名、函數名 首字母必須大寫

類 Class

類名首字母必須大寫

Class Abc{  # 首字母大寫
    Number a     
    Characters b

}

類裏面可以定義子類:重點是必須有結束語 end `

class Abc{
    # 定義子類
    class Abc_sub  # 首字母還是必須大寫
        ...
    end    
    # 必須有結束符號 end
    # 必須有結束符號 end
    # 必須有結束符號 end
}
  • 局部變量局部變量是在方法中定義的變量。局部變量在方法外是不可用的。在後續的章節中,您將看到有關方法的更多細節。局部變量以 小寫字母_ 開始。

  • 實例變量實例變量可以跨任何特定的實例或對象中的方法使用。這意味着,實例變量可以從對象到對象的改變。實例變量在變量名之前放置符號 (@)

  • 類變量類變量可以跨不同的對象使用,但,不能跨類使用。類變量屬於類,且是類的一個屬性。類變量在變量名之前放置符號 (@@)

  • 全局變量可以跨類使用。如果您想要有一個可以跨類使用的變量,您需要定義全局變量。全局變量總是以美元符號 ($) 開始。

類函數 def

??? Function 是什麼東西?

# -*- coding: UTF-8 -*- # 必須在首行
Class Abc{              # 首字母大寫
    Number a     
    Characters b
    # ??? 這是啥鬼???
    Function aa{        # 首字母大寫
        puts 'aa 函數'
    }
    Function bb{        # 首字母大寫
        puts 'bb 函數'
    }

    def aa
        puts 'hello'
    end
}

類創建對象

new 方法屬於類方法

object1= Abc. new 

初始化函數

將在調用帶參數的類的 new 方法時執行

class Abc
    @@static_var = 0;   # 類變量
    def initialize(a,b,c)
    @a = a   # 實例變量
    @b = b 
    @c = c
# 實例化
class Abc.new('a','b','c')

樣例

# -*- coding: UTF-8 -*- # 必須在首行
# 無參數的實例方式
class Abc
    def hi
        puts 'hi,i\'m yeSir'
    end
end
# 實例化對象
object = Abc. new  
object.hi # hi,i'm yeSir



# 有參數的實例方式
# TODO
class Abc
    @@classVar=0
    def initalize(f,s,t)
        @f = f;
        @s = s;
        @t = t;
    end

    def display_args()
        puts "display_args() classVar is: #@@classVar"
        puts "first aguments #@f"
        puts "second aguments #@s"
        puts "third aguments #@t"

    end

    def testClassVar()
        @@classVar += 1;
        puts "classVar is #@@classVar"
    end
end
obj1 = Abc.new('a','b','c')
obj2 = Abc.new('d','e','f')

obj2.testClassVar
obj1.testClassVar


obj1.display_args
obj1.display_args

條件判斷

if 循環

常規寫法

# -*- coding: UTF-8 -*-
if condition 
    code
elsif condition
    code
else
    code

簡寫形式

if condition then code end;
code if condition

unless(if相反)

condition 爲假時,執行code

unless condition [then]
    code
else
    code
end

簡潔寫法

code unless condition

case 語句

# -*- coding: UTF-8 -*-
case expression
when condition
    code
when condition
    code
else 
    code
end

簡潔的寫法

case   # 此處沒有條件
when true then code 
when false then code
when true then code
end

# 例子
case 
when false then puts 'no'
when true then puts 'yes'
when true then puts 'no2'
end

while 語句

while condition [do或:]
    code
end

簡寫形式

code while condition
# 或者   該語句可以在 while 判斷之前先執行一次 begin 內的函數;
begin 
    code
end while condition

until 語句

while 的相反語句
condition 爲假時,執行code

until condition [do]
    code
end

函數

必須使用小寫字母開頭,如果以大寫字母開頭,會被解析成變量;
必須調用之前,就申明一個函數,否則會報錯;

函數參數不定,枚舉

# -*- coding: UTF-8 -*- # 必須在首行
def sample (*test)
   puts "參數個數爲 #{test.length}"
   for i in 0...test.length
      puts "參數值爲 #{test[i]}"
   end
end
sample "Zara", "6", "F"
sample "Mac", "36", "M", "MCA"

函數的一般調用

# -*- coding: UTF-8 -*- # 必須在首行
def test(a=1,b=2)
    puts a+b;
end

# 調用函數
test a b

函數返回

# -*- coding: UTF-8 -*- # 必須在首行
def test
   i = 100
   j = 200
   k = 300
return i, j, k
end
var = test
puts var

類方法

類方法,內部默認是 public,定義在類的外部,默認是 private

可以通過 Module 的 private 和 public 來改變類方法的默認標記

不聲明,訪問類方法

class Accounts
   def reading_charge
        code
   end
   def Accounts.return_date
        code
   end
end
# 調用
Accounts.return_date
# #########

私有類和共有類改變

class MyClass

  def public_method
  end

  private

  def private_method_1
  end

  def private_method_2
  end

  protected

  def protected_method
  end

end

類的繼承

class Pet
  attr_accessor :name, :age

  def say(word)
    puts "Say: #{word}"
  end
end

class Cat < Pet
  def say(word)
    puts "Meow~"
    super
  end
end

class Dog < Pet
  def say(word, person)
    puts "Bark at #{person}!"
    super(word)
  end
end

Cat.new.say("Hi")
Dog.new.say("Hi", "ihower")

# 輸出

Meow~
Say: Hi
Bark at ihower!
Say: Hi

undef 取消方法定義

undef 方法名

函數 TODO …

常規使用的塊

# -*- coding: UTF-8 -*-

def test
   puts "a"
   yield
   puts "b"
   yield
end
test {puts "c"}  #result : a c b c

單個塊調試

# 單個塊調試、調用
blockTest = lambda {
    puts '單純的一個block'
}
# 調用
blockTest.call()

給塊傳參

def test
   yield 5
   puts "在 test 方法內"
   yield 100
end
test {|i| puts "你在塊 #{i} 內"}

函數 + 塊

塊名作爲參數,放到最後一個參數,以 &參數 傳入
def test(&a)
    a.call  # 塊調用
    puts '最後調用'
end
test { puts "Hello World!"}

模塊

定義模塊

  • 常量 首字母大寫
  • 函數 模塊名後加點,再接一個函數
# test.rb
module Trig  # Trig 是模塊名
   PI = 3.141592654 # 常量 首字母大寫
   def Trig.sin(x)  # 函數定義,模塊.函數
   # ..
   end
   def Trig.cos(x)  # 函數定義,模塊.函數
   # ..
   end
end

引入模塊

  • 模塊引入 : require 文件名
  • 常量 : 以 雙冒號 引入 (::常量名)
  • 方法 : 以 點 引入 (.函數名)
  • 類裏引入 : 在類裏面可以 include 引入
require test[.rb]
a = Trig.sin(Trig::PI/4)   # 模塊函數


class Test
include Trig  # 引入模塊
def test 
    puts Trig::PI
end
#調用
dd = Test.new
dd.test

參考文章:

菜鳥教程:http://www.runoob.com/ruby/ruby-tutorial.html
ruby 快速入門:https://ihower.tw/rails/ruby-cn.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章