# 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
是 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
$ gem install bundler -v 1.17
$ gem install minitest -v 5.8.4
# 使用 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 | 如果先前的條件不成立,則執行以下代碼 |
elsif | if 表達式的替代條件 |
end | 用于結束以 begin 、class 、def 、do 、if 等關鍵字開頭的代碼塊 |
ensure | 總是在塊終止時執行 |
false | 邏輯布爾假值 |
for | 開始一個 for 循環 |
if | 如果 if 的條件語句為 true ,則執行代碼塊 |
in | 與 for 循環一起使用 |
module | 定義一個模塊 |
next | 跳轉到循環條件評估之前的點 |
nil | 為空或無效或始終為假 |
not | 邏輯否定運算符 |
or | 邏輯或運算符 |
redo | 條件循環后跳轉 |
rescue | 在引發異常后評估表達式 |
retry | ? 在救援之外調用時,重復方法調用 ? 在救援內部調用時,跳轉到塊頂部 |
return | 從方法或代碼塊返回值 |
self | 當前對象 |
super | 調用超類中的同名方法 |
then | 與 if 、unless 、when 、case 、rescue 一起使用的分隔符 |
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 | 當前方法的接收者對象 |
true | TrueClass 的實例 |
false | FalseClass 的實例 |
nil | NilClass 的實例 |
__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 值(除了 nil 和 false 之外的所有值)都是 true |
FALSE | 虛假本身 |
NIL | 零本身 |
STDIN | 標準輸入。$stdin 默認值 |
STDOUT | 標準輸出。$stdout 默認值 |
STDERR | 標準錯誤輸出。$stderr 默認值 |
ENV | 類哈希對象包含當前環境變量。 在 ENV 中設置值會更改子進程的環境 |
ARGF | $< 的別名 |
ARGV | $* 的別名 |
DATA | 腳本的文件對象,就在 END 之后。 除非未從文件中讀取腳本,否則未定義 |
VERSION | Ruby 版本字符串 |
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 | 文檔 |
---|---|---|---|
Integer | a = 17 | a.class > Integer a.class.superclass > Numeric | |
Float | a = 87.23 | a.class > Float a.class.superclass > Numeric | |
String | a = "Hello universe" | a.class > String | |
Array | a = [12, 34] | a.class > Array | |
Hash | a = {type: "tea", count: 10} | a.class > Hash | |
Boolean | a = false a = true | a.class > FalseClass a.class > TrueClass | |
Symbol | a = :status | a.class > Symbol | |
Range | a = 1..3 | a.class > Range | |
Nil | a = nil | a.class > NilClass |
# 兩(liang)者(zhe)都是同義(yi)詞(ci)
a = 37
a.kind_of? Integer
# true
a.is_a? Integer
# true
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 name | Output |
---|---|
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 |
(1..20).step(2) { |number| puts "#{number}"}
# 輸出(chu)
# 1
# 3
# 5
# 7
# 9
# 11
# 13
# 15
# 17
# 19
num = 2
puts 'two' if num == 2
如果條件為真(zhen),則執行代(dai)碼
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 返回最后執行的(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 input
when 19 then puts "It's 19"
end
case input
when 19 then puts "It's 19"
else
puts "It's not 19"
end
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"
函數名稱 | Output | Note |
---|---|---|
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)、空格(" ") |
prepend | a = "world" <br> a.prepend("hello ") "hello world" | 在另一個字符串之前添加字符串 |
insert | a = "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_suffix | string = "sausage is expensive" string.delete_suffix(" is expensive") "sausage" | 從字符串中刪除后綴 |
delete_prefix | string = "sausage is expensive" string.delete_prefix("sausage") " is expensive" | 從字符串中刪除前綴 |
split | string = "a b c d" <br> string.split ["a", "b", "c", "d"] | 將字符串轉換為字符數組 |
join | arr = ['a', 'b', 'c'] <br> arr.join => "abc" | 將數組轉換為字符串 |
to_i | a = "49" <br> a.to_i => 49 | 將字符串轉換為整數 |
chop | "abcd?".chop("?") => "abcd" | 從字符串中刪除最后一個字符 |
count | str = "aaab" <br> str.count("a") 3 | 計算字符串中的字符 |
to_f | a = "49" a.to_f 49.0 | 將字符串轉換為浮點數 |
to_sym | a = "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
# return value
def give_me_data
data = yield
puts "data = #{data}"
end
give_me_data { "Big data" }
# 輸出 => data = Big data
do
和 end
(用于多行)或花括號 {
和 }
(用于單行)之間的代碼稱為塊,它們可以在兩個管道之間定義多個參數 (|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
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 "
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
l = lambda { puts "Hello World" }
# 速記
l = -> { puts "Hello World" }
# 調(diao)用 lambda
l.call
# 輸(shu)出 => Hello World
有多(duo)種方法可以調用 lambda
l.()
l[]
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)
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
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
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]
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]
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]
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]
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]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.shift #=> 1
numbers
#=> [2, 3, 4, 5, 6, 7, 8, 9, 10]
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]
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]
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]
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
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]
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]
# 當你(ni)有單行塊時
salary = [399, 234, 566, 533, 233]
salary.each { |s| puts s }
# 輸出
# 399
# 234
# 566
# 533
# 233
當你有一個多行塊時,你可以用 do
和 end
替換花括號 {}
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 }
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
salary = [399, 234, 566, 533, 233]
salary.each_index { |i| puts i}
# 輸出
# 0
# 1
# 2
# 3
# 4
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]
salary = [399, 234, 566, 533, 233]
salary.collect { |s| s > 400 }
# 輸出
# [false, false, true, true, false]
for value in [2, 3, 5, 7]
puts value
end
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
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
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
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
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
data_sample = [2, 3, 5, 7]
0.upto((data_sample.size - 1) / 2) { |index| puts "#{data_sample[index]}" }
# 輸出
# 2
# 3
data_sample = [2, 3, 5, 7]
(data_sample.size - 1).downto(data_sample.size / 2) { |index| puts "#{data_sample[index]}" }
# 輸出
# 7
# 5
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
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
numbers = [2, 2, 2, 2, 2]
numbers.reduce(11, :+)
# 輸出
# 21
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
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.find { |name| name.start_with?("E") and name.end_with?("h") }
# output
# Earth
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
# []
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]
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]
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]
numbers = [1, 2, 3, 1, 2, 3, 0]
numbers.drop_while { |n| n < 3 }
# 是 3 小于 3,返回 false,所以刪除 1, 2
# [3, 1, 2, 3, 0]
words = %w[first second third fourth fifth sixth]
str = ""
words.reverse_each {|word| str += "#{word} "}
p str #=> "sixth fifth fourth third second first "
Name | When to use |
---|---|
all? | 當您想檢查所有元素是否滿足您的條件時 |
any? | 當您想檢查至少一項是否滿足您的條件時 |
one? | 當您想檢查一個元素是否滿足您的要求時 |
none? | 當您想檢查是否沒有任何項目滿足您的條件時,相反? |
empty? | 當你想檢查對象是否為空時 |
include? | 當你想檢查元素是否存在于對象中時 |
[2, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
# true
[1, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
# false
[1, 3, 5, 7, 10].any? { |num| num % 2 == 0 }
# true
[1, 3, 5, 7, 19].any? { |num| num % 2 == 0 }
# false
[1, 3, 2, 5, 7].one? { |num| num % 2 == 0 }
# true
[1, 3, 2, 5, 4].one? { |num| num % 2 == 0 }
# false
[1, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
# true
[2, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
# false
[].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]
[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]
[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]
[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]
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]]
# 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
# 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
# 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
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
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