亚洲成A人片在线观看网站_成年网站免费视频A在线双飞_日日日日做夜夜夜夜无码_久久夜色撩人精品国产小说

Ruby 備忘清單

入門

安裝

# Debian, Ubuntu
$ sudo apt-get install ruby-full
# Windows
$ winget install RubyInstallerTeam.Ruby 
$ brew install ruby # macOS
$ docker run -it --rm ruby:latest # Docker
$ docker run -it --rm ruby:2.7

使用包管理器安裝

$ brew install rbenv ruby-build # macOS
# Debian、ubuntu 和(he)其他衍生(sheng)產品
$ sudo apt install rbenv

使(shi)用 安裝 ruby

# 列出最新的穩定版本
$ rbenv install -l
# 列出所(suo)有本地版本
$ rbenv install -L
# 安裝 Ruby 版本
$ rbenv install 3.1.2
$ rbenv global 3.1.2 # 為這(zhe)臺機器設置默認Ruby版本
# 或者
$ rbenv local 3.1.2 # 設置此目錄的(de) Ruby 版(ban)本(ben)
$ rbenv local --unset
$ rbenv version # 顯(xian)示當前活動的(de) Ruby 版本
=> 1.9.3-p327 (set by /Users/sam/.rbenv/version)

使用 安裝 ruby

$ curl -sSL //get.rvm.io | bash -s stable
$ rvm list          # Ruby 版本列(lie)表
$ rvm install 3.0.1 # 安(an)裝 3.0.1
$ rvm use 3.0.1     # 使(shi)用 3.0.1

如何安裝 ruby gem 管理器, gem

# 訪問 bash 以執行(xing)以下命令
$ docker run -it --rm ruby:latest bash
$ gem install bundler
$ bundle -v
$ gem update bundler
$ gem uninstall bundler

什么是 Gemfile 和 Gemfile.lock

是 Bundler(也是 gem)的(de)配置文件,其中包含項目的(de) gem 列表(依(yi)賴項)

# 在項目根目錄的 Gemfile 中指定 gem
ruby '2.5.6'

source '//rubygems.org'
gem 'nokogiri'
gem 'rack', '~>1.1'
gem 'rspec', :require => 'spec'

安裝(zhuang) Gemfile 中(zhong)的所有 gem

$ bundle install

安裝特定 ruby gem 的特定版本

$ gem install bundler -v 1.17
$ gem install minitest -v 5.8.4

使用 Bundler 更新 gem

# 使用 Bundler 更新單(dan)個 gem
$ bundle update nokogiri
# 使用 Bundler 更新 Gemfile 中的每個(ge) gem
$ bundle update

保留字

保留字描述
__ENCODING__當前文件的腳本編碼
__LINE__當前文件中此關鍵字的行號
__FILE__當前文件的路徑
BEGIN包含在 { } 中的代碼在程序運行之前運行
END包含在 { } 中以在程序結束時運行
alias為現有方法、運算符、全局變量創建別名
and邏輯與運算符
begin開始一段代碼
break終止循環
case將表達式與匹配的 when 子句進行比較,其中
end 結束
class定義一個類
def定義函數/方法
defined?檢查某個變量、函數是否存在
do開始一個代碼塊并執行塊中的代碼,以
end關鍵字結束
else如果先前的條件不成立,則執行以下代碼
elsifif 表達式的替代條件
end用于結束以 beginclassdefdoif 等關鍵字開頭的代碼塊
ensure總是在塊終止時執行
false邏輯布爾假值
for開始一個 for 循環
if如果 if 的條件語句為 true,則執行代碼塊
infor 循環一起使用
module定義一個模塊
next跳轉到循環條件評估之前的點
nil為空或無效或始終為假
not邏輯否定運算符
or邏輯或運算符
redo條件循環后跳轉
rescue在引發異常后評估表達式
retry? 在救援之外調用時,重復方法調用
? 在救援內部調用時,跳轉到塊頂部
return從方法或代碼塊返回值
self當前對象
super調用超類中的同名方法
thenifunlesswhencaserescue 一起使用的分隔符
true邏輯布爾真
undef使當前類中的方法/函數未定義
until在條件語句為假時執行代碼塊
when在 case 語句下開始一個子句
while執行代碼塊,直到條件語句變為假
yield執行傳遞給方法的代碼塊

注釋

# 單行注釋
=begin
多行(xing)
注釋(shi)
=end
=begin 注釋第 1=end
puts "Hello world!"  # 代碼(ma)的內聯注釋

運算符

邏輯運算符

  • and
  • or
  • not
  • &&
  • ||
  • !

位運算符

  • &
  • |
  • ^
  • ~
  • <<
  • >>

算術運算符

  • +
  • -
  • *
  • /
  • %
  • **

比較運算符

  • ==
  • !=
  • >
  • <
  • >=
  • <=
  • <=>
  • ===
  • eql?
  • equal?

運算符示例

# 添加
1 + 1   #=> 2
# 減法
2 - 1   #=> 1
# 乘法
2 * 2   #=> 4
# 分(fen)配
10 / 5  #=> 2
17 / 5    #=> 3, not 3.4
17 / 5.0  #=> 3.4
# 指數
2 ** 2  #=> 4
3 ** 4  #=> 81
# 模數(shu)(求除法(fa)的余(yu)數(shu))
8 % 2   #=> 0  (8 / 2 = 4; 沒(mei)有剩余)
10 % 4  #=> 2  (10 / 4 = 2 余數為 2)
a = 10
b = 20
a == b #=> false
a != b #=> true
a > b #=> false
a < b #=> true
a >= b #=> false
a <= b #=> true

# 比較運(yun)算符
a <=> b #=> -1
c = 20
c <=> b #=> 0
c <=> a  #=> 1
# 用于(yu)測試 case 語句的(de) when 子句中的(de)相等性
(1...10) === 5 #=> true
# 如果接收者和(he)參數具有相同的類型和(he)相等的值(zhi),則為(wei)真(zhen)
1.eql?(1.0) #=> false
c = a + b  #=> 30
c += a #=> 40
c -= a #=> 30
c *= a #=> 300
c /= a #=> 30
c %= a #=> 3
c **= a #=> 59049

# Ruby 并行賦(fu)值
a = 10
b = 20
c = 30
a, b, c = 10, 20, 30
# Ruby 位運算(suan)符
a = 60
b = 13
# & 如果兩個操作數中(zhong)都存(cun)在,則二進制 AND 運(yun)算符將(jiang)位(wei)復(fu)制到結(jie)果中(zhong)。
a & b #=> 12
# | 如果二進制或運算符存(cun)在于任(ren)一操作(zuo)數中,則(ze)復制一個位。
a | b #=> 61
# ^ 二元異或操作(zuo)符(fu)如果在一(yi)個(ge)操作(zuo)數中設置(zhi)(zhi),則復(fu)制該位,但(dan)不能同(tong)時在兩個(ge)操作(zuo)數中設置(zhi)(zhi)。
a ^ b #=> 49
# ~ 二進(jin)制補碼運算符(fu)是(shi)一元(yuan)的,具有(you)“翻轉”位的效果。
~a
# << 二進(jin)制左移運算符(fu)。 左操作數的值被移動
# 左操作(zuo)數指定的位數。
a << 2
# >> 二進制右移(yi)運算符。 左操作數的值被(bei)移(yi)動
# 右操作數(shu)指定的位數(shu)。
a >> 2

# Ruby 邏輯運算符
a and b #=> true.
a or b #=> true.
a && b #=> true.
(a || b) #=> true.
!(a && b) #=> false.
not(a && b) #=> false.
# Ruby 三元運(yun)算(suan)符
# ? :
# 如果條(tiao)件為真? 然后(hou)值 X :否則(ze)值 Y
a == 10 ? puts 'Right' : puts 'Wrong'
# Ruby 范圍運算符
# .. 創建從起點到終點的(de)范圍(含)
1..10 #=> 創建從 1 到(dao) 10 的范圍(包(bao)括(kuo) 1 到(dao) 10)
# ... 創建(jian)一(yi)個從起點到終點的范圍(wei),不包括在內
1...10 #=> 創建一個從 1 到 10 的(de)獨占范(fan)圍

運算符優先級表

  • !, ~, unary +
  • **
  • unary -
  • *, /, %
  • +, -
  • <<, >>
  • &
  • ^
  • >, >=, <, <=
  • <=>, ==, ===, !=, =~, !~
  • &&
  • ?, :
  • modifier-rescue
  • =, +=, -=, *=, /=, %=
  • defined
  • not
  • or, and
  • modifier-if, modifier-unless, modifier-while, modifier-until
  • { }
  • do ... end

變量和范圍

名字范圍示例說明
[a-z]_本地的count = 10_count = 10必須初始化局部變量
@實例變量@id = []實例變量在初始化之前具有“nil”值
@@類變量@@name = []必須初始化類變量
$全局變量$version = "0.8.9"全局變量在初始化之前具有“nil”值
[A-Z]持續的PI = 3.14常量變量必須初始化,您可以更改常量,但您會收到警告

有五種(zhong)不同類型(xing)的變量。第一個字(zi)符確定范圍

局部變量

current_weather = "rainy"
_weather = "sunny"

必(bi)須(xu)以(yi)下(xia)劃(hua)線(xian)或小(xiao)寫字母開頭

實例變量

# 實例(li)類變量
@current_weather = "rainy"
# 全局變量
$current_weather = "rainy"
# 常量變量
WEATHER = "rainy".freeze

偽變量

名字說明
self當前方法的接收者對象
trueTrueClass 的實例
falseFalseClass 的實例
nilNilClass 的實例
__FILE__當前源文件名
__LINE__當前源文件的當前行號

選項變量

名字說明
$-0$/ 的別名
$-a如果設置了選項 -a,則為真。只讀變量
$-d$DEBUG 的別名
$-F$; 的別名
$-i在就地編輯模式下,此變量保存擴展,否則為零
可以指定啟用(或禁用)就地編輯模式
$-I$: 的別名
$-l如果選項 -lis 設置為真。只讀變量
$-p如果選項 -pi 設置為真。只讀變量
$-v$VERBOSE 的別名

預定義變量

名字說明
$!異常信息消息。raise 設置此變量
$@最后一個異常的回溯,它是 String 的數組,指示調用方法的位置。格式中的元素如:“filename:line”或“filename:line:in `methodname'”(助記符:發生異常的地方)
$&與此范圍內最后一次成功的模式匹配匹配的字符串,如果最后一次模式匹配失敗,則返回 nil。 (助記符:在某些編輯器中類似于 &)這個變量是只讀的
$`當前范圍內最后一次成功的模式匹配所匹配的任何內容之前的字符串,如果最后一次模式匹配失敗,則為 nil。 (助記符:` 通常在帶引號的字符串之前)此變量是只讀的
$'當前范圍內最后一次成功的模式匹配所匹配的字符串后面的字符串,如果最后一次模式匹配失敗,則為 nil。 (助記符:' 通常跟在帶引號的字符串之后)
$+最后一個成功的搜索模式匹配的最后一個括號,如果最后一個模式匹配失敗,則為 nil。如果您不知道一組替代模式中的哪一個匹配,這很有用。 (助記:積極向上)
$1, $2...包含上一次成功匹配的模式中相應括號集中的子模式,不計算已經退出的嵌套塊中匹配的模式,或者如果最后一次模式匹配失敗,則為 nil。 (助記符:如 \digit)這些變量都是只讀的
$~當前范圍內最后一個匹配的信息。設置此變量會影響匹配變量,如 $&、$+、$1、$2.. 等。第 n 個子表達式可以通過 $~[nth] 檢索。 (助記符:~ 用于匹配)這個變量是局部作用域的
$=不區分大小寫的標志,默認為 nil。 (助記符:= 用于比較)
$/輸入記錄分隔符,默認為換行符。像 awk 的 RS 變量一樣工作。如果設置為 nil,則將立即讀取整個文件。 (助記符:/ 用于在引用詩歌時劃定行界)
$\print 和 IO#write 的輸出記錄分隔符。默認值為無。 (助記符:它就像 /,但它是你從 Ruby 中“返回”的東西)
$,打印的輸出字段分隔符。此外,它是 Array#join 的默認分隔符。 (助記符:當您的打印語句中有 , 時打印的內容)
$;String#split 的默認分隔符。
$.讀取的最后一個文件的當前輸入行號。
$<由命令行參數或標準輸入給出的文件的虛擬連接文件(如果沒有提供參數文件)。 $<.file 返回當前文件名。 (助記符:$< 是一個 shell 輸入源)
$>print 的默認輸出,printf$stdout 默認情況下。 (助記符:$> 用于 shell 輸出)
$_通過gets或readline輸入String的最后一行。如果gets/readline 遇到EOF,它被設置為nil。這個變量是局部作用域的。 (助記符:部分與 Perl 相同)
$0包含包含正在執行的 Ruby 腳本的文件的名稱。在某些操作系統上,分配給 $0 會修改 ps(1) 程序看到的參數區域。作為一種指示當前程序狀態的方式,這比隱藏您正在運行的程序更有用。 (助記符:與 sh 和 ksh 相同)
$*為腳本提供的命令行參數。 Ruby 解釋器的選項已被刪除。 (助記符:與 sh 和 ksh 相同)
$$運行此腳本的 Ruby 的進程號。(助記符:與貝殼相同)
$?最后執行的子進程的狀態。
$:該數組包含通過 load 或 require 查找 Ruby 腳本和二進制模塊的位置列表。 它最初由任何 -I 命令行開關的參數組成,然后是默認的 Ruby 庫,probabl "/usr/local/lib/ruby",然后是 ".",表示當前目錄 . (助記符:冒號是 PATH 環境變量的分隔符)
$"該數組包含由 require 加載的模塊名稱。 用于防止 require 兩次加載模塊。助記符:防止文件被雙引號(加載)
$DEBUG-d 開關的狀態。
$FILENAME$<.filename 相同
$LOAD_PATH$: 的別名
$stdin當前的標準輸入
$stdout當前的標準輸出
$stderr當前標準錯誤輸出
$VERBOSE詳細標志,由 -v 開關設置到 Ruby 解釋器

預定義的全局常量

名字說明
TRUE典型的真值。在 Ruby 中,所有非 false 值(除了 nilfalse 之外的所有值)都是 true
FALSE虛假本身
NIL零本身
STDIN標準輸入。$stdin 默認值
STDOUT標準輸出。$stdout 默認值
STDERR標準錯誤輸出。$stderr 默認值
ENV類哈希對象包含當前環境變量。 在 ENV 中設置值會更改子進程的環境
ARGF$< 的別名
ARGV$* 的別名
DATA腳本的文件對象,就在 END 之后。 除非未從文件中讀取腳本,否則未定義
VERSIONRuby 版本字符串
RUBY_RELEASE_DATE發布日期字符串
RUBY_PLATFORM平臺標識符

檢查變量的范圍

defined? count
"local-variable"
defined? @id
"instance-variable"
defined? @@name
"class variable"
defined? $version
"global-variable"
defined? PI
"constant"

數據類型

類型示例Class文檔
Integera = 17a.class > Integer
a.class.superclass > Numeric
Floata = 87.23a.class > Float
a.class.superclass > Numeric
Stringa = "Hello universe"a.class > String
Arraya = [12, 34]a.class > Array
Hasha = {type: "tea", count: 10}a.class > Hash
Booleana = false
a = true
a.class > FalseClass
a.class > TrueClass
Symbola = :statusa.class > Symbol
Rangea = 1..3a.class > Range
Nila = nila.class > NilClass

檢查數據類型

# 兩(liang)者(zhe)都是同義(yi)詞(ci)
a = 37
a.kind_of? Integer
# true
a.is_a? Integer
# true

Symbol

week_days = {sunday: 11, monday: 222}

整數有用的方法

2.even?
# true
3.even?
# false

范圍

.. 用于創建包含范圍

range = 1..10
range.to_a
# 輸出 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

... 用于創建專屬范圍

range = 1...10
range.to_a
# 輸出 => [1, 2, 3, 4, 5, 6, 7, 8, 9]

一些有用的方法

Method nameOutput
cover?(1..5).cover?(5) => true
end('a'..'z').end => "z"
first(1..5).first => 1
first(3)('A'..'Z').first(2) => ["A", "B"]
eql?((0..2).eql?(0..5) => false

在 Range 中使用 step

(1..20).step(2) { |number| puts "#{number}"}
# 輸出(chu)
# 1
# 3
# 5
# 7
# 9
# 11
# 13
# 15
# 17
# 19

條件結構

if 修飾符

num = 2
puts 'two' if num == 2 

如果條件為真(zhen),則執行代(dai)碼

if elsif else 語句

temp = 19
if temp >= 25
  puts "hot"
elsif temp < 25 && temp >= 18
  puts "normal"
else
  puts "cold"
end
# 輸出 => normal

除非語句

# 除非與 if 相(xiang)反,當語句為假時(shi)進(jin)行評估
name = "rob"
# if name != "bob"
unless name == "bob"
  puts "hello stranger"
else
  puts "hello bob"
end
# 輸出 => hello stranger
num = 6
puts 'not two' unless num == 2
# 輸出 => not two

case 陳述

# case 返回最后執行的(de)表達式的(de)值(zhi)
case input
# 檢查一個整數,19
when 19
  puts "It's 19"
  # 檢查浮點數,33.3
when 33.3
  puts "It's 33.3"
  # 檢(jian)查一個確切的(de)字(zi)符串,“Zaman”
when "Zaman"
  puts "Hi Zaman"
when 10
  puts "It's 10"
  # 檢查(cha)范(fan)圍(wei)
when 7..11
  puts "It's between 7 and 11"
  # 檢(jian)查多(duo)個值(zhi),“咖啡(fei)”
when "tea", "coffee"
  puts "Happy days"
  # 檢查(cha)正則表達式“aA6”
when /^a[A-Z]+[0-6]+$/
  puts "It's a valid match"
  # 通(tong)過與 String 類(lei)“任何字(zi)符串”
  # 進行比較來檢查任何(he)字符串
when String
  puts "It's a String"
end

case 簡短的語法

case input
  when 19 then puts "It's 19"
end

case 可選的失敗

case input
  when 19 then puts "It's 19"
else
  puts "It's not 19"
end

case 獲取返回值

marks = 86
result = case marks
        when 0..49 then "Fail"
        when 50..64 then "Pass"
        when 65..74 then "Credit"
        when 75..84 then "Distinction"
        when 85..100 then "High Distinction"
        else "Invalid marks"
        end

puts result
# High Distinction

字符串

字符串插值

name = "World"
puts "Hello #{name}"
puts "The total is #{1+1}"
# "the total is 2"

字(zi)符(fu)串插值(zhi)允許您將字(zi)符(fu)串組合在一起

提取子字符串

string = "abc123"
string[0,3]
# "abc"
string[3,3]
# "123"
string[0..-2]
# "abc12"
#remove or replace the substring
string[0..2] = ""
puts string
# "123"

子字符串是字符串的(de)一小部(bu)(bu)分,如果你只想要那(nei)個特定的(de)部(bu)(bu)分,它會很有用,比如開頭(tou)、中間或結尾

將字符串轉換為小寫或大寫

"HELLO World".downcase  # "hello world"
"hello worlD".upcase    # "HELLO WORLD"
"hEllo wOrlD".capitalize # "Hello world"
"hEllo WOrlD".swapcase  # "HeLLO woRLd"

有用的方法

函數名稱OutputNote
length or size"HELLO World".length => 11
"HELLO World".size => 11
返回字符串的長度
reverse"hello worlD".reverse => "Dlrow olleh"返回反轉的字符串
include? other_str"hEllo wOrlD".include? "w" => true如果字符串或字符存在則返回 true,否則返回 false
gsub(pattern, replacement)"hEllo wOrlD".gsub(" ", "_") => "hEllo_wOrlD"gsub 或全局替換用提供的字符串替換一個或多個字符串
gsub(pattern, hash)"organization".gsub("z", 'z' => 's') => "organisation"gsub 或全局替換用提供的哈希替換一個或多個字符串
gsub(pattern) { |match| block}"Price of the phone is 1000 AUD".gsub(/\d+/) { |s| '$'+s }
"Price of the phone is $1000 AUD"
gsub 或全局替換用提供的塊替換一個或多個字符串
strip" hEllo WOrlD ".strip
"hEllo WOrlD"
它將刪除(修剪)以下任何前導和尾隨字符:null(“\x00”)、水平制表符(“\t”)、換行符(\n)、垂直制表符(“\v”)、換頁符(f)、回車(\r)、空格(" ")
prependa = "world" <br> a.prepend("hello ")
"hello world"
在另一個字符串之前添加字符串
inserta = "hello" <br> a.insert(a.length, " world")
"hello world"
在特定位置插入字符串
start_with?string = "ruby programming"
string.start_with? "ruby"
true
檢查字符串是否以特定前綴開頭
end_with?string = "ruby programming"
string.end_with? "ruby"
false
檢查字符串是否以特定前綴結尾
delete_suffixstring = "sausage is expensive"
string.delete_suffix(" is expensive")
"sausage"
從字符串中刪除后綴
delete_prefixstring = "sausage is expensive"
string.delete_prefix("sausage")
" is expensive"
從字符串中刪除前綴
splitstring = "a b c d" <br> string.split
["a", "b", "c", "d"]
將字符串轉換為字符數組
joinarr = ['a', 'b', 'c'] <br> arr.join => "abc"將數組轉換為字符串
to_ia = "49" <br> a.to_i => 49將字符串轉換為整數
chop"abcd?".chop("?") => "abcd"從字符串中刪除最后一個字符
countstr = "aaab" <br> str.count("a")
3
計算字符串中的字符
to_fa = "49"
a.to_f
49.0
將字符串轉換為浮點數
to_syma = "key"
a.to_sym
:key
將字符串轉換為符號
match"abcd?".match(/ab/) => #<MatchData "ab">將模式轉換為正則表達式并在字符串上調用其匹配方法
empty?"hello".empty? => false如果字符串的長度為零,則返回 true
squeeze"Booook".squeeze => "Bok"返回字符串的副本,其中相同字符的運行被單個字符替換
*puts "Ruby " * 4 => Ruby Ruby Ruby Ruby返回多個 self 副本的串聯
+"sammy " + "shark" => "sammyshark"返回 self 和給定的其他字符串的連接
eql?s = 'foo' => true
s.eql?('foo') => true
如果對象具有相同的長度和內容,則返回 true;作為自己;否則為假
+"sammy " + "shark" => "sammyshark"返回 self 和給定的其他字符串的連接
+"sammy " + "shark" => "sammyshark"返回 self 和給定的其他字符串的連接

方法

聲明一個方法

def method_name(parameter1, parameter2)
    puts "#{parameter1} #{parameter2}"
    parameter1 + parameter2
end

res = method_name(20, 10)
# 輸出(chu) => 30
def method_name(parameter1, parameter2)
    puts "#{parameter1} #{parameter2}"
    return parameter1 + parameter2
end
# 輸出 => 30

調用方法

res = method_name(parameter1, parameter2)
# 可以調用不(bu)帶(dai)括號的方法
res = method_name parameter1, parameter2

類方法

類(lei)方(fang)法是類(lei)級(ji)別的方(fang)法。 有多種定(ding)義類(lei)方(fang)法的方(fang)法

class Mobile
    def self.ring
        "ring ring ring..."
    end
end

Mobile.ring

class Mobile
    def Mobile.ring
        "ring ring ring..."
    end
end
Mobile.ring

class Mobile
    class << self
    def ring
        "ring ring ring..."
       end
    end
end
Mobile.ring

類(lei)(lei)方法是(shi)類(lei)(lei)對象的(de)實例方法。 當創建一個新類(lei)(lei)時,“Class”類(lei)(lei)型(xing)的(de)對象被初始化并分配給(gei)一個全局常(chang)量(在(zai)本(ben)例中為 Mobile)

Mobile = Class.new do
    def self.ring
        "ring ring ring..."
    end
end
Mobile.ring
Mobile = Class.new
class << Mobile
    def ring
        "ring ring ring..."
    end
end
Mobile.ring

使用另一個參數作為默認值

def method_name(num1, num2 = num1)
    return num1 + num2
end
res = method_name(10)
# 輸出 => 20

為方法參數定義默認值

def method_name(parameter1, parameter2, type = "ADD")
    puts "#{parameter1} #{parameter2}"
    return parameter1 + parameter2 if type == "ADD"
    return parameter1 - parameter2 if type == "SUB"
end
res = method_name(20, 10)
# 輸出 => 30

將可變長度參數傳遞給方法參數

def method_name(type, *values)
    return values.reduce(:+) if type == "ADD"
    return values.reduce(:-) if type == "SUB"
end
numbers = [2, 2, 2, 3, 3, 3]
res = method_name("ADD", *numbers)
# 輸出 => 15
res = method_name("SUB", *numbers)
# 輸(shu)出 => -11
# 或者您(nin)可以提(ti)供這樣的值
res = method_name("ADD", 2, 2, 2, 3, 3, 3)
# 輸出 => 15

修改對象

a = ["Drama", "Mystery", "Crime",
"Sci-fi", "Disaster", "Thriller"]
a.sort
puts a
# 我們沒有修(xiu)改(gai)對象(xiang)
# Drama
# Mystery
# Crime
# Sci-fi
# Disaster
# Thriller
a.sort!
puts a
# 修(xiu)改(gai)對象
# Crime
# Disaster
# Drama
# Mystery
# Sci-fi
# Thriller

當您要修改對象時,在方法之后使用 !

布爾方法

在 ruby 中,以問(wen)號(hao) (?) 結尾的方法稱為(wei)布爾方法,它返(fan)回 true 或 false

"some text".nil?
# false
nil.nil?
# true

您可以擁有自己的布爾方法

def is_vowel?(char)
    ['a','e','i','o','u'].include? char
end
is_vowel? 'a'
# true
is_vowel? 'b'
# false

Blocks (塊)

塊示例

# return value
def give_me_data
    data = yield
    puts "data = #{data}"
end
give_me_data { "Big data" }
# 輸出 => data = Big data

doend(用于多行)或花括號 {}(用于單行)之間的代碼稱為塊,它們可以在兩個管道之間定義多個參數 (|arg1, arg2|)

單行塊

salary = [399, 234, 566, 533, 233]
salary.each { |s| puts s }
# puts s = block body
# |s| = block arugments

多行塊

salary.each do |s|
    a = 10
    res = a * s
    puts res
end
# 塊體(ti)
# a = 10
# res = a * s
# puts res
# 塊參數
# |s|

塊可以作(zuo)為方法(fa)參數傳遞,也(ye)可以與方法(fa)調用相關聯。 塊返回(hui)最后評估的語(yu)句

隱式傳遞一個塊

def give_me_data
    puts "I am inside give_me_data method"
    yield
    puts "I am back in give_me_data method"
end

give_me_data { puts "Big data" }

# 輸(shu)出
# I am inside give_me_data method
# Big data
# I am back in give_me_data method

多次調用

def give_me_data
    yield
    yield
    yield
end

give_me_data { puts "Big data" }

# 輸出
# Big data
# Big data
# Big data

使用塊參數調用

def give_me_data
    yield 10
    yield 100
    yield 30
end

give_me_data { |data| puts "Big data #{data} TB" }

# 輸出
# Big data 10 TB
# Big data 100 TB
# Big data 30 TB

使用多個塊參數調用

def give_me_data
    yield "Big data", 10, "TB"
    yield "Big data", 100, "GB"
    yield "Big data", 30, "MB"
end

give_me_data { |text, data, unit| puts "#{text} #{data} #{unit}" }

# 輸出(chu)
# Big data 10 TB
# Big data 100 GB
# Big data 30 MB

塊將嘗試從當前上下文返回

give_me_data
    puts "我在 give_me_data 方法里(li)面"
end

def test
  puts "我在(zai)測試方法(fa)里面"
  give_me_data { return 10 } # 代碼從(cong)這里返回
  puts "I am back in test method"
end

return_value = test

# 輸出(chu)
# 我在測試方法里面(mian)
# 我在 give_me_data 方(fang)法里面
# 10

通過使用 & 參數顯式傳遞塊

def give_me_data(&block)
    block.call
    block.call
end

give_me_data { puts "Big data" }

# 輸出
# Big data
# Big data

檢查是否給出了塊

def give_me_data
    yield
end

give_me_data

# 輸出
# LocalJumpError: no block given (yield)

處理異常并使塊可選的方法

def give_me_data
    return "no block" unless block_given?
    yield
end

give_me_data { puts "Big data" }
give_me_data

# 輸出
# Big data

Procs

Procs 示例

p = Proc.new { puts "Hello World" }

def give_me_data(proc)
    proc.call
end

give_me_data p

# 輸出
# Hello World

proc 就像一個可(ke)以存儲在變量中的塊

任意參數

p = Proc.new { |count| "Hello World " * count }

def give_me_data(proc)
    proc.call 5, 2
end

give_me_data p

# 輸出
# "Hello World Hello World Hello World Hello World Hello World "

proc 將嘗試從當前上下文返回

p = Proc.new { return 10 }
p.call
# 輸出
LocalJumpError: unexpected return

不能從頂級上下文返回

def give_me_data
    puts "我(wo)在 give_me_data 方法里面"
    p = Proc.new { return 10 }
    p.call # 代碼(ma)從這里返回(hui)
    puts "I am back in give_me_data method"
end

return_value = give_me_data
puts return_value

# 輸(shu)出
# 我在 give_me_data 方法里面(mian)
# 10

Lambdas

聲明一個 lambda

l = lambda { puts "Hello World" }
# 速記
l = -> { puts "Hello World" }
# 調(diao)用 lambda
l.call
# 輸(shu)出 => Hello World

有多(duo)種方法可以調用 lambda

l.()
l[]

嚴格的 arguments

l = -> (count) { "Hello World " * count }
l.call 5
# 輸(shu)出
# "Hello World Hello World Hello World Hello World Hello World "
l.call 5, 2
# 輸出
wrong number of arguments (given 2, expected 1)

塊中聲明一個 lambda

def give_me_data
    puts "I am inside give_me_data method"
    l = -> { return 10 }
    l.call
    puts "I am back in give_me_data method"
end

return_value = give_me_data
puts return_value

# 輸出
# I am inside give_me_data method
# I am back in give_me_data method
# nil # because puts return nil

lambdas 從 lambda 本身返回,就像常規方法一樣

l = -> { return 10 }
l.call

# 輸(shu)出 => 10

數組

初始化一個空數組

array = Array.new   #=> []
# or
array = []

包含不同類型的對象的數組

array = [1, "two", 3.0] 
#=> [1, "two", 3.0]

用初始大小和默認對象填充數組

numbers = Array.new(3)       
#=> [nil, nil, nil]
numbers = Array.new(3, 7)    
#=> [7, 7, 7]
numbers = Array.new(3, true) 
#=> [true, true, true]
numbers = []
numbers.fill(7, 0..2)   #=> [7, 7, 7]

不同哈希值的數組

array_with_hashes = Array.new(2) { {} } #=> [{}, {}]
array_with_hashes[0][:name] = "Bob"
array_with_hashes[0][:id] = 10          #=> [{:name=>"Bob", :id=>10}, {}]

二維數組

temperature_data = [
              ["A908", 38],
              ["A909", 37],
              ["A910", 38],
          ]
temperature_data[0]    #=> ["A908", 38]
temperature_data[0][0] #=> "A908"
temperature_data[0][1] #=> 38

數組索引

str_array = [
  "This", "is", "a", "small", "array"
]
str_array[0]            #=> "This"
str_array[1]            #=> "is"
str_array[4]            #=> "array"

負索引

str_array = [
  "This", "is", "a", "small", "array"
]
# 索(suo)引 -1 表示最后一個元素(su)
str_array[-1]        #=> "array"
# 索(suo)引 -2 表示倒數(shu)第二個元素
str_array[-2]        #=> "small"
str_array[-6]        #=> nil

數組方法 at

str_array = [
  "This", "is", "a", "small", "array"
]

puts str_array.at(0)      #=> "This"

范圍獲取

arr = [1, 2, 3, 4, 5, 6]
arr[100]                  #=> nil
arr[-3]                   #=> 4
arr[2, 3]                 #=> [3, 4, 5]
arr[1..4]                 #=> [2, 3, 4, 5]
arr[1..-3]                #=> [2, 3, 4]

數組方法 fetch

arr = ['a', 'b', 'c', 'd', 'e', 'f']
arr.fetch(100)
#=> IndexError: 數組(zu)邊(bian)界外的索引 100:-6...6
arr.fetch(100, "oops")    #=> "oops"

超出邊界,給默認值

獲取數組元素

arr = [1, 2, 3, 4, 5, 6]

arr.first     # 第一個(ge)值 => 1
arr.last      # 最后一個(ge)值 => 6
# take 返回前 n 個元素
arr.take(3)   #=> [1, 2, 3]
# drop 在 n 個元素被刪除之(zhi)后(hou)
arr.drop(3)   #=> [4, 5, 6]

在數組末尾添加值 push

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.push(11)          
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
numbers.push(12, 13, 14)  
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

數組末尾刪除值 pop

num_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_array.pop             #=> 10
num_array
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

在數組的開頭添加值 unshift

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.unshift(0)          
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.unshift(-3, -2, -1) 
#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

檢索并同時刪除第一個元素 shift

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.shift #=> 1
numbers
#=> [2, 3, 4, 5, 6, 7, 8, 9, 10]

刪除特定索引處的元素 delete_at

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.delete_at(2) #=> 4
numbers             
#=> [2, 3, 5, 6, 7, 8, 9, 10]

刪除數組中任意位置的特定元素

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.delete(2) #=> 2
numbers           #=> [3, 5, 6, 7, 8, 9, 10]

在給定索引處插入值 insert

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.insert(0, 0)           
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.insert(0, -3, -2, -1)  
#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.insert(-1, 12, 13, 14) 
#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]
numbers.insert(-4, 11)         
#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

一個塊來填充數組的值

numbers = Array.new(10) { |n| n = n * 2 } 
#=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

填充數組變得更容易

numbers = Array(100..110)
#=> [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

# 或者我們可(ke)以將范圍轉換為(wei)數組
(100..110).to_a 
#=> [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

從數組中刪除 nil 值

arr = ['foo', 0, nil, 'bar', 7, nil]
arr.compact  #=> ['foo', 0, 'bar', 7]
arr      #=> ['foo', 0, nil, 'bar', 7, nil]
arr.compact! #=> ['foo', 0, 'bar', 7]
arr      #=> ['foo', 0, 'bar', 7]

去重 uniq

arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]

檢查數組中是否存在值(include?

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.include? "Mars"
# 輸出 => true
planets.include? "Pluto"
# 輸出 => false

獲取數組大小

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.size
# 輸出 => 8
planets.length
# 輸出(chu) => 8

您可(ke)以使用大小或(huo)長度,兩者(zhe)都是同義詞(ci)

清除數組

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.clear
# 輸出 => []

獲取數組的第一個元素

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[0]
# or
numbers.first
# 輸出 => 1

獲取數組的最后一個元素

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers[-1]
# or
numbers.last
# 輸出(chu) => 10

合并兩個數組

a = ["tom", "mot", "otm"]
b = [2, 3, 5]
a.zip(b)
# 輸(shu)出
# [["tom", 2], ["mot", 3], ["otm", 5]]

對數組進行排序

primes = [7, 2, 3, 5]
sorted_primes = primes.sort
puts "#{sorted_primes}"
# 輸出 => [2, 3, 5, 7]

or in-place sort

primes = [7, 2, 3, 5]
primes.sort!
puts "#{primes}"
# 輸(shu)出 => [2, 3, 5, 7]
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.sort
# 輸出
# ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Saturn", "Uranus", "Venus"]
planets.sort_by { |p| p }
# 輸出(chu)
# ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Saturn", "Uranus", "Venus"]
planets.sort_by { |p| p.length }
# 輸(shu)出
# ["Mars", "Earth", "Venus", "Saturn", "Uranus", "Neptune", "Jupiter", "Mercury"]

從數組中獲取最大值

primes = [7, 2, 3, 5]
primes.max_by { |p| p }
# 輸出(chu) => 7

使用范圍獲取數組元素

# numbers[start..end], both index are inclusive
puts numbers[0..3]
# 1
# 2
# 3
# 4
# numbers[start..end], end index is exclusive
puts numbers[0...3]
# 1
# 2
# 3
# or numbers[start..length]
puts numbers[0, 1]
# 1

獲取數組的前n個元素

primes = [7, 2, 3, 5]
primes.take(3)
# [7, 2, 3]

訪問元素

primes = [7, 2, 3, 5]
primes.fetch(3)
# 5
# Fetch will throw an error if the element does not exist
primes.fetch(10)
# (index 10 outside of array bounds: -4...4)
# or get an default value
primes.fetch(10, -1)
# -1

從數組中刪除重復元素

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 1]
numbers.uniq
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

刪除前 n 個元素

primes = [7, 2, 3, 5]
primes.drop(3)
# [5]

刪除第一個元素

primes = [7, 2, 3, 5]
primes.shift
# [2, 3, 5]

刪除最后一個元素

primes = [7, 2, 3, 5]
primes.pop
# [7, 2, 3]

刪除帶有索引的元素

primes = [7, 2, 3, 5]
primes.delete_at(-1)
# [7, 2, 3]

刪除所有出現的元素

primes = [7, 2, 3, 5, 5]
primes.delete(5)
# [7, 2, 3]

each

# 當你(ni)有單行塊時
salary = [399, 234, 566, 533, 233]
salary.each { |s| puts s }
# 輸出
# 399
# 234
# 566
# 533
# 233

當你有一個多行塊時,你可以用 doend 替換花括號 {}

salary.each do |s|
  a = 10
  res = a * s
  puts res
end
# 輸(shu)出(chu)
# 3990
# 2340
# 5660
# 5330
# 2330

或者您可以使用大(da)括號 {} 和分(fen)號作為分(fen)隔(ge)符而不是換行符來做同樣的事(shi)情

salary.each { |s| a = 10 ; res = a * s ; puts res }

each_with_index

salary = [399, 234, 566, 533, 233]
salary.each_with_index { |value, index| puts "#{index} #{value}" }
# 輸出(chu)
# 0 399
# 1 234
# 2 566
# 3 533
# 4 233

each_index

salary = [399, 234, 566, 533, 233]
salary.each_index { |i| puts i}
# 輸出
# 0
# 1
# 2
# 3
# 4

map

salary = [399, 234, 566, 533, 233]
salary.map { |s|  s * 10  }
# 返回
# [3990, 2340, 5660, 5330, 2330]
# 另一方(fang)面,每(mei)個(ge)都(dou)返(fan)回(hui)原始值
salary = [399, 234, 566, 533, 233]
salary.each { |s|  s * 10  }
# 返(fan)回
# [399, 234, 566, 533, 233]

collect

salary = [399, 234, 566, 533, 233]
salary.collect { |s| s > 400 }
# 輸出
# [false, false, true, true, false]

for

for value in [2, 3, 5, 7]
    puts value
end

each_with_object

colors = [
  {color: "red", count: 3}, {color: "red", count: 5}, {color: "black", count: 4}
]
colors.each_with_object(Hash.new(0)) { |color, hash| hash["color_"+color[:color]] = color[:color].upcase; hash["count_"+color[:color]] += color[:count] }
# 輸(shu)出
{"color_red"=>"RED", "count_red"=>8, "color_black"=>"BLACK", "count_black"=>4}

[1, 2, 3].each_with_object(0) { |number, sum| sum += number}
# 輸出
# 0
# 因為0是(shi)不(bu)可變的(de),由(you)于(yu)初(chu)始對象是(shi)0,所(suo)以(yi)方法返(fan)回0

while

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
index = 0
while index < planets.size
    puts "#{planets[index]}"
    index += 1
end

a = 1
star = '*'
while a <= 10
    puts star
    star += '*'
    a += 1
end

do while

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
index = 0
loop do
    puts "#{planets[index]}"
    index += 1
    break if planets[index] == "Mars" or index > planets.size
end

until

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
index = planets.size - 1
until index < 0
    puts "#{planets[index]}"
    index -= 1
end
a = 1
star = '*'
until star.length > 10
    puts star
    star += '*'
    a += 1
end

times

10.times { puts "#{rand(1..100)}"}
# 輸出
# 將(jiang)打(da)印 10 個隨機數

僅僅因為你可以并不意味著你應(ying)該像(xiang)這(zhe)樣迭(die)代一個(ge)數組(zu)

data_sample = [2, 3, 5, 7]
data_sample.size.times { |index| puts "#{data_sample[index]}" }
# 輸出
# 2
# 3
# 5
# 7

upto

data_sample = [2, 3, 5, 7]
0.upto((data_sample.size - 1) / 2) { |index| puts "#{data_sample[index]}" }
# 輸出
# 2
# 3

downto

data_sample = [2, 3, 5, 7]
(data_sample.size - 1).downto(data_sample.size / 2) { |index| puts "#{data_sample[index]}" }
# 輸出
# 7
# 5

step

1.step(20, 2) { |number| puts "#{number}"}
# 輸出
# 1
# 3
# 5
# 7
# 9
# 11
# 13
# 15
# 17
# 19

19.step(1, -2) { |number| puts "#{number}"}
# 輸(shu)出
# 19
# 17
# 15
# 13
# 11
# 9
# 7
# 5
# 3
# 1

inject

numbers = [2, 2, 2, 2, 2]
numbers.inject{ |res, n| res + n }
# 輸出是所有數(shu)字之和的(de)結果(guo)
# 如果不給res設置(zhi)初(chu)始(shi)(shi)值,則數組(zu)的第一個元素作為res的初(chu)始(shi)(shi)值
# 10
# 現在將 res 的值(zhi)設置為 11
numbers = [2, 2, 2, 2, 2]
numbers.inject(11) { |res, n| res + n }
# so 11 + 2, 13 + 2, 15 + 2, 17 + 2 and 19 + 2
# 21
# using symbol
numbers = [2, 2, 2, 2, 2]
numbers.inject(:+)
# 輸出(chu)
# 10

使用初始值和符號

numbers = [2, 2, 2, 2, 2]
numbers.inject(11, :+)
# 輸(shu)出(chu)
# 21

reduce

numbers = [2, 2, 2, 2, 2]
numbers.reduce(11, :+)
# 輸出
# 21

detect

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.detect { |name| name.start_with?("E") and name.end_with?("h") }
# output
# Earth
salary = [399, 234, 566, 533, 233]
salary.detect { |s| s > 1000 }
# output
# nil

find

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.find { |name| name.start_with?("E") and name.end_with?("h") }
# output
# Earth

select

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.select { |n| n % 2 == 0 }
# 現(xian)在你有(you)一個偶(ou)數(shu)數(shu)組
# [2, 4, 6, 8, 10]
# 如(ru)果沒有滿足您的邏輯(ji)的值(zhi),則返(fan)回一個空(kong)數(shu)組
[1, 1, 1].select { |n| n % 2 == 0 }
# no even numbers
# []

reject

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.reject { |n| n % 2 == 0 }
# 如果數(shu)(shu)字是偶數(shu)(shu)則(ze)拒絕(jue),所以現在我們有一個奇(qi)數(shu)(shu)數(shu)(shu)組
# [1, 3, 5, 7, 9]

keep_if

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.keep_if { |n| n % 2 == 0 }
# numbers 數(shu)(shu)組僅包含偶數(shu)(shu)
# [2, 4, 6, 8, 10]

delete_if

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.delete_if { |n| n % 2 == 0 }
# numbers 數(shu)組僅(jin)包含(han)奇(qi)數(shu)
# [1, 3, 5, 7, 9]

drop_while

numbers = [1, 2, 3, 1, 2, 3, 0]
numbers.drop_while { |n| n < 3 }
# 是 3 小于 3,返回 false,所以刪除 1, 2
# [3, 1, 2, 3, 0]

reverse_each

words = %w[first second third fourth fifth sixth]
str = ""
words.reverse_each {|word| str += "#{word} "}
p str #=> "sixth fifth fourth third second first "

布爾可枚舉方法

布爾可枚舉方法

NameWhen to use
all?當您想檢查所有元素是否滿足您的條件時
any?當您想檢查至少一項是否滿足您的條件時
one?當您想檢查一個元素是否滿足您的要求時
none?當您想檢查是否沒有任何項目滿足您的條件時,相反?
empty?當你想檢查對象是否為空時
include?當你想檢查元素是否存在于對象中時

all?

[2, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
# true
[1, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
# false

any?

[1, 3, 5, 7, 10].any? { |num| num % 2 == 0 }
# true
[1, 3, 5, 7, 19].any? { |num| num % 2 == 0 }
# false

one?

[1, 3, 2, 5, 7].one? { |num| num % 2 == 0 }
# true
[1, 3, 2, 5, 4].one? { |num| num % 2 == 0 }
# false

none?

[1, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
# true
[2, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
# false

empty?

[].empty?
# true
[1, 3, 5, 7, 9].empty?
# false

組合方法

組合方法

  • & 返回一個新數組,其中包含在數組和數組 other_array 中找到的每個元素;省略重復;使用 eql? 比較項目
  • intersection 返回一個新數組,其中包含在 self 和所有給定數組 other_arrays 中找到的每個元素;省略重復;使用 eql? 比較項目
  • + 返回一個數組,該數組包含 self 的所有元素,后跟給定數組的所有元素
  • - 返回一個數組,其中包含在給定數組中找不到的所有 self 元素
  • union 返回一個數組,其中包含 self 的所有元素和給定數組的所有元素,已刪除重復項
  • difference 返回一個數組,其中包含在任何給定數組中找不到的所有 self 元素
  • product 返回或產生來自 self 和給定數組的所有元素組合

&

[0, 1, 2, 3] & [1, 2] # => [1, 2]
[0, 1, 0, 1] & [0, 1] # => [0, 1]

intersection

[0, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3])
# => [0, 1]
[0, 0, 1, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3])
# => [0, 1]

+

a = [0, 1] + [2, 3]
a # => [0, 1, 2, 3]

-

[0, 1, 1, 2, 1, 1, 3, 1, 1] - [1] 
# => [0, 2, 3]
[0, 1, 2, 3] - [3, 0] 
# => [1, 2]
[0, 1, 2] - [4] 
# => [0, 1, 2]

union

[0, 1, 2, 3].union([4, 5], [6, 7]) 
# => [0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 1].union([2, 1], [3, 1]) 
# => [0, 1, 2, 3]
[0, 1, 2, 3].union([3, 2], [1, 0]) 
# => [0, 1, 2, 3]

difference

[0, 1, 1, 2, 1, 1, 3, 1, 1].difference([1])
# => [0, 2, 3]
[0, 1, 2, 3].difference([3, 0], [1, 3])
# => [2]
[0, 1, 2].difference([4])
# => [0, 1, 2]

product

a = [0, 1, 2]
a1 = [3, 4]
p = a.product(a1)
p.size # => 6 # a.size * a1.size
p # => [[0, 3], [0, 4], [1, 3], [1, 4], [2, 3], [2, 4]]

循環

while 循環

# variable count
count = 4
# using while loop
# here conditional is count i.e. 4
while count >= 1
  # statements to be executed
  puts "Ruby Cheatsheet"
  count = count - 1
  # while loop ends here
end

輸出

Ruby Cheatsheet
Ruby Cheatsheet
Ruby Cheatsheet
Ruby Cheatsheet

for 循環

# loop using range as expression
text = "Ruby Cheatsheet"
# using for loop with the range
for count in 1..5 do
  puts text
end

輸出

Ruby Cheatsheet
Ruby Cheatsheet
Ruby Cheatsheet
Ruby Cheatsheet
Ruby Cheatsheet

do..while 循環

# starting of do..while loop
loop do
  puts "Ruby Cheatsheet"
  val = '7'
  # using boolean expressions
  if val == '7'
    break
  end
  # ending of ruby do..while loop
end

輸出

Ruby Cheatsheet

until 循環

var = 7
# here do is optional
until var == 11 do
  # code to be executed
  puts var * 10
  var = var + 1
  # here loop ends
end

輸出

70
80
90
100

跳出循環

salary = [399, 234, 566, 533, 233]
salary.each do |s|
  break if s == 566
  puts s
end
# 輸(shu)出
# 399
# 234

通過使用 break 關鍵字

在循環內跳過

salary = [399, 234, 566, 533, 233]
salary.each do |s|
  next if s == 533
  puts s
end
# 輸(shu)出
# 399
# 234
# 566
# 233

通過使用(yong) next 關鍵字

重復當前迭代

data = [456, 3000]
retry_count = 0
status = "network failure"
sum = 0
data.each do |d|
    if retry_count == 3
        status = "connection established"
        retry_count = 0
        redo
    elsif status == "network failure" and retry_count < 5
        puts "network failure #{retry_count}"
        retry_count += 1
        redo
    elsif status == "connection established"
        puts d
        sum += d
    end
end
# output of sum
# 3456

重新開始循環

numbers = [2, 2, 44, 44]
sum = 0
begin
    numbers.each do |s|
        if rand(1..10) == 5
            puts "hi 5, let's do it again!"
            sum = 0
            raise "hi 5"
        end
        puts s
        sum += s
    end
rescue
    retry
end

Classes

Classes 示例

class Person
    # when you create a new object, it looks for a method named initialize and executes it, like a constructor in java
    # def initialize(name, number)
    #    @name = name
    #    @number = number
    # end
    # instance variable
    # @name
    # class variable
    # @@count
    # attr_accessor acts as a getter and setter for the following instance attributes
    attr_accessor :name, :number
    # class variable must be initialized
    @@count = 0
    def self.count
        @@count
    end
    def self.count=(count)
        @@count = count
    end
    def initialize
        @@count += 1
    end
end
# create an instance of the Person class
p1 = Person.new
# set attributes of the Person class
p1.name = "Yukihiro Matsumoto"
p1.number = 9999999999
# get attributes of the Person class
puts "#{p1.name}"
puts "#{p1.number}"
puts "#{Person.count}"
# Yukihiro Matsumoto
# 9999999999
# 1
p2 = Person.new
p2.name = "Yukihiro Matsumoto"
p2.number = 9999999999
# get attributes of the Person class
puts "#{p2.name}"
puts "#{p2.number}"
puts "#{Person.count}"
# Yukihiro Matsumoto
# 9999999999
# 2
# set class variable
Person.count = 3
puts "#{Person.count}"
# 3

繼承一個類

class Person
    attr_accessor :name, :number
end
# 使用 < 符號從(cong)父類繼承方法和屬性
class Student < Person
    attr_accessor :id
end
s = Student.new
s.name = "James Bond"
s.number = 700
s.id = 678
puts "#{p.name}"
James Bond
puts "#{p.number}"
700
puts "#{p.id}"
678

檢查實例類型

class Vehicle; end
class Car < Vehicle; end
class Audi < Car; end
car = Car.new
car.instance_of? Vehicle
false
car.instance_of? Car
true
car.instance_of? Audi
false
a = 7
a.instance_of? Integer
true
a.instance_of? Numeric
false

如果(guo)對(dui)象是給定(ding)類的實例,而不是子類或超類,則返回 true

打印一個類的所有方法名

puts (String.methods).sort
# 排除(chu)從(cong) Object 類繼(ji)承的(de)方法(fa)
puts (String.methods - Object.public_instance_methods).sort

檢查一個類是否有特定的方法

String.respond_to?(:prepend)
true
String.respond_to?(:append)
false

另見

  • (ruby-lang.org)
  • (github.com)