Ruby語言是由松本行弘(Matz)設計,是一門通用的、面向對象的、解釋型語言。php
1.Ruby:用來表示編程的語言
2.ruby:是指一個計算機程序,特指Ruby的解釋器
3.RUBY:準確來講沒有這種寫法,通常是簡寫,例如WTO.html
brew install ruby
rvm install 2.2.4
更多rvm能夠參考:rvm入門篇-安裝和使用ios
1.irb:交互式Ruby控制檯程序。git
2.rvm: Ruby Version Manager程序員
3.VSCodegithub
4.gem:一套Ruby庫和應用程序包管理實用工具編程
5.rake:Ruby的make工具,一套任務管理實用工具數組
6.rdoc和ri:Ruby文檔工具ruby
執行ruby文件數據結構
ruby basic.rb
語法檢查而不運行程序:
ruby -cw basic.rb
它會讀取文件並指出語法是否有錯。更多相似-cw的解釋器開關參見文末:解釋器的命令行開關。
局部變量以小寫字母或者下劃線開頭,包含字母、下劃線或數字。Ruby不是使用的駝峯命名,而是使用下劃線將多個單詞拼接。例如:
✅first_name ❎firstName
實例變量一般以一個單獨的@開頭,後面字符和局部變量命名規則一致。例如:
class Person def initialize(temp_name,temp_age) @name = temp_name end def printn return @name end end # 實例變量 p1 = Person.new("zhangsan",24) p p1.printn #輸出結果爲:zhangsan
類變量命名規則與實例變量一致,可是它以@@符號開頭:
class Person @@person_number = 0 def initialize(temp_name,temp_age) @name = temp_name @@person_number = @@person_number + 1 end def print_person_number return @@person_number end end # 實例變量 p1 = Person.new("zhangsan",24) p p1.print_person_number 輸出結果:1
以$開頭,它就是一個全局變量,例如:
$FIRST_NAME $population
常量以大寫字母開頭,若是遇到命名多詞組合常量,可使用駝峯命名法,也可使用下劃線分割且全部字母大寫。
A String FirstName FIRST_NAME
Ruby中的方法名聽從與局部變量相同的規則和約定。例如:
def get_first_name return @first_name end
方法調用使用.運算符。例如:
p1.get_name #方法調用 p1.name #屬性調用
可使用$:查看加載路徑。
這裏主要介紹三種引用方式:load、require、require_relative。
load命令老是會加載所請求的文件,不論這個文件是否已經加載過。假如一個文件在幾回加載過程當中發生改變,那麼最新版本的文件將優先使用並覆蓋以前加載的版本。尤爲是在irb會話中,當在編輯器中修改一個文件時,想要當即測試修改的效果,使用load很是有用。
常常會使用的一個技術,用於請求Ruby擴展或庫,不管是標準庫仍是三方庫。
requrire就算調用屢次也不會從新加載已經加載過的文件。Ruby會持續追蹤已經被請求的那些文件而不會重複加載它們。
require不能辨識出當前的工做目錄(.)。用戶能夠顯式地指定它。例如:
require "./loadee.rb" or $: << "." #把當前目錄添加到加載路徑當中。 require "loadee.rb"
這個命令會搜索相對於所在文件的目錄來加載功能。這個不用把當前目錄添加到加載路徑中。
查看某個屬性或者變量是什麼類型,可使用.class方法。
字符串插值:
name = "zhangsan" age = "20" person_desc = "my name is #{name},age is #{age}" puts person_desc
bang方法:
Ruby的方法能夠以驚歎號(!)結尾,這樣的方法稱爲bang方法。有驚歎號的方法被標記爲危險的。由於他可能會改變原有數據的值。例如:
str = "Hello World" p str.upcase! p str #---------------------- p str.upcase p str
更多字符串方法參見:https://ruby-doc.org/core-2.2.0/String.html
Set不是Ruby的核心類,它是一個標準庫類,因此使用的時候須要require "set"。它的對象是惟一的。
構造一個集合:
require 'set' s = [1,2,3,4,5,6,7,8,9,124,45,6,4,1] set = Set.new(s) p set
集合沒有字面構造器。
數組的建立:
#中括號建立 ["zhangsan","lisi","wangwu"]
注意%W 和%w的區別:
name = "Tim" students = %W{zhangsan lisi wangwu #{name}} students = %w{zhangsan lisi wangwu #{name}}
%w:建立字符串數組的特殊方式
%W:若是想要對字符串進行解析,使用W
數組遍歷:
[1,2,3,4,5,8].each {|item| puts item+"!"}
更多數組方法參見:https://docs.ruby-lang.org/en/2.0.0/Array.html
散列在其餘語言中有時被稱爲:字典或者Map。散列由鍵值組成。例如:
state_hash = {"January" => "Jan","February" => "Feb","March" => "Mar"} state_hash["April"] = "Apr" puts state_hash["April"] #Result is Apr puts state_hash.class #Result is Hash
符號是Ruby內置類Symbol的實例。它有一個字面構造器:冒號引導符。能夠經過這個記號,從字面航辨認出符號與字符串、變量名、方法名或者其餘的區別。
符號最經常使用的用法:方法參數和散列鍵:
#方法參數 puts "abc".send(:upcase) #等價於puts "abc".send(upcase.to_sym) #輸出結果:ABC #-------------------- #散列鍵 d_hash = {:name => "zhangsan", :age => 25} puts d_hash[:age] #輸出結果:25
1.Ruby處理符號更快,所以若是要大量處理散列的查找,就會節省一些時間。若是須要性能上的優化,使用符號做爲散列鍵則多是個好辦法。
2.Ruby容許一種特殊的符號表現形式在散列鍵的位置出現,它能夠在符號以後使用冒號,同事能夠替代散列的分割箭頭符,例如:
d_hash = {name: "zhangsan",age: 23} #等價於 d_hash = {"name" => "zhangsan","age" => 23}
class Student attr_accessor :s_name,:s_age, :s_class def initialize(name,age,t_class) @s_name = name @s_age = age @s_class = t_class end def study puts "study" end end s1 = Student.new("zhangsan",15,"1年級") p s1.s_name s1.study
Ruby語言聽從單繼承原則,沒法繼承多個類,也就意味着它只是一個超類。
class Student < People end
原始添加方法:
class Ticket def initialize(ve,date) @venue = ve @date = date end def price=(pr) @price = pr end def venue @venue end def date @date end def price @price end end
class Ticket attr_reader :venue, :date, :price #讀取方法 attr_writer :venue, :date, :price #寫方法 def initialize(ve,date) @venue = ve @date = date end end ti = Ticket.new("北京大學","2019-09-01") ti.venue = "sdfsdfd" puts ti.venue
class Ticket attr_accessor :price,:venue,:date def initialize(ve,date) @venue = ve @date = date end end ti = Ticket.new("北京大學","2019-09-01") ti.price = 200 puts ti.price
區別於attr,attr: price只生成了reader,attr: price,true會生成getter和setter。
Ruby鼓勵讀者進行模塊化設計:將大的組件分解爲小的,並能夠混合(mixin)和匹配對象的行爲。和類同樣,模塊是一組方法和常量的集合。
模塊是使用混合到類的方式。
模塊沒有實例
建立模塊使用module關鍵字:
module Category def say_hello puts "Category's Hello" end end class Student include Category #引用模塊 def initialize end end st = Student.new st.say_hello
module ModuleGoOne def go puts "ModuleGoOne's go" end end module ModuleGoTwo def go puts "ModuleGoTwo's go" end end class Student < Person include ModuleGoOne prepend ModuleGoTwo def go puts "Student's go" end end st = Student.new st.goto # Result is ModuleGoTwo's go
module ModuleGoOne def go puts "ModuleGoOne's go" end end module ModuleGoTwo def go puts "ModuleGoTwo's go" end end class Person def go puts "Person's go" end end class Student < Person include ModuleGoOne prepend ModuleGoTwo def go puts "Student's go" end end st = Student.new st.go
方法查找規則:
1.先查找當前類中是否有該方法,若是有,則直接調用,執行完畢;
2.查找module中是否有該方法,若是有,則調用,執行完畢;
3.查找父類中是否有該方法,父類中是否有module,若是有prepend模塊,則先調用,沒有的話若是有在類中定義,則調用;
4.所屬的超類
5.內置Kernel模塊
6.BasicObject
7.method_missing NoMethodError
塊由大量代碼組成。
塊中的代碼老是包含在大括號內
塊的調用:須要與其相同名稱的方法調用
可使用yield語句來調用塊
每一個Ruby源文件能夠聲明當文件被加載時要運行的代碼塊(BEGIN),以及程序完成執行後要運行的代碼塊(END)。
BEGIN { puts "BEGIN..." } END { puts "END......." } def test yield end test {puts "Hello"} =begin def test puts "在test方法內" yield puts "又回到了test方法" yield end test {puts "你在塊內"} =end =begin def test puts "在test方法內" yield 10 puts "又回到了test方法" yield 20 end test {|i| puts "你在塊內#{i}"} =end
它是一個指令集,裏面包含了一些比較實用的命令,能夠方便用戶的一些操做,例如:查找無用圖片、查找無用類、在某個文件或者文件夾中查找某個字符串、查找某個文件等。
連接:https://rubygems.org/gems/itools
gem install itools
NAME itools - a collection of tools for ios developer SYNOPSIS itools [global options] command [command options] [arguments...] VERSION 0.4.7 GLOBAL OPTIONS --help - Show this message --version - Display the program version COMMANDS count_code_line - count lines of code find - search unuse image help - Shows a list of commands or help for one command parse - Analyze the memory footprint of each part or component in Xcode project pre_commit - 經過執行該命令,hook 本地commit,而後進行規範化 search - search str(or strs) in some file(or folder's file) search_file - search File in folder search_unuse_class - search unuse class size_for - calculate the memory footprint of file or folder(contain file)
更多參見:https://github.com/ScottZg/itools
1.gems:https://rubygems.org/
2.官方文檔:https://docs.ruby-lang.org/en/
Pre-defined variables $! The exception information message set by 'raise'. $@ Array of backtrace of the last exception thrown. $& The string matched by the last successful match. $` The string to the left of the last successful match. $' The string to the right of the last successful match. $+ The highest group matched by the last successful match. $1 The Nth group of the last successful match. May be > 1. $~ The information about the last match in the current scopke. $= The flag for case insensitive, nil by default. $/ The input record separator, newline by default. $\ The output record separator for the print and IO#write. Default is nil. $, The output field separator for the print and Array#join. $; The default separator for String#split. $. The current input line number of the last file that was read. $< The virtual concatenation file of the files given on command line (or from $stdin if no files were given). $> The default output for print, printf. $stdout by default. $_ The last input line of string by gets or readline. $0 Contains the name of the script being executed. May be assignable. $* Command line arguments given for the script sans args. $$ The process number of the Ruby running this script. $? The status of the last executed child process. $: Load path for scripts and binary modules by load or require. $" The array contains the module names loaded by require. $DEBUG The status of the -d switch. $FILENAME Current input file from $<. Same as $<.filename. $LOAD_PATH The alias to the $:. $stderr The current standard error output. $stdin The current standard input. $stdout The current standard output. $VERBOSE The verbose flag, which is set by the -v switch. $-0 The alias to $/. $-a True if option -a is set. Read-only variable. $-d The alias to $DEBUG. $-F The alias to $;. $-i In in-place-edit mode, this variable holds the extension, otherwise nil. $-I The alias to $:. $-l True if option -l is set. Read-only variable. $-p True if option -p is set. Read-only variable. $-v The alias to $VERBOSE. $ -w True if option -w is set.
Usage: ruby [switches] [--] [programfile] [arguments] -0[octal] specify record separator (\0, if no argument) -a autosplit mode with -n or -p (splits $_ into $F) -c check syntax only -Cdirectory cd to directory before executing your script -d set debugging flags (set $DEBUG to true) -e 'command' one line of script. Several -e's allowed. Omit [programfile] -Eex[:in] specify the default external and internal character encodings -Fpattern split() pattern for autosplit (-a) -i[extension] edit ARGV files in place (make backup if extension supplied) -Idirectory specify $LOAD_PATH directory (may be used more than once) -l enable line ending processing -n assume 'while gets(); ... end' loop around your script -p assume loop like -n but print line also like sed -rlibrary require the library before executing your script -s enable some switch parsing for switches after script name -S look for the script using PATH environment variable -T[level=1] turn on tainting checks -v print version number, then turn on verbose mode -w turn warnings on for your script -W[level=2] set warning level; 0=silence, 1=medium, 2=verbose -x[directory] strip off text before #!ruby line and perhaps cd to directory -h show this message, --help for more info