# 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
使用包管理器安裝 rbenv
$ brew install rbenv ruby-build # macOS
# Debian、ubuntu 和其他衍生產(chǎn)品
$ sudo apt install rbenv
使用 rbenv 安裝 ruby
# 列出最新的穩(wěn)定版本
$ rbenv install -l
# 列出所有本地版本
$ rbenv install -L
# 安裝 Ruby 版本
$ rbenv install 3.1.2
$ rbenv global 3.1.2 # 為這臺機(jī)器設(shè)置默認(rèn)Ruby版本
# 或者
$ rbenv local 3.1.2 # 設(shè)置此目錄的 Ruby 版本
$ rbenv local --unset
$ rbenv version # 顯示當(dāng)前活動的 Ruby 版本
=> 1.9.3-p327 (set by /Users/sam/.rbenv/version)
使用 RVM 安裝 ruby
$ curl -sSL https://get.rvm.io | bash -s stable
$ rvm list # Ruby 版本列表
$ rvm install 3.0.1 # 安裝 3.0.1
$ rvm use 3.0.1 # 使用 3.0.1
如何安裝 ruby gem 管理器, bundler gem
# 訪問 bash 以執(zhí)行以下命令
$ docker run -it --rm ruby:latest bash
$ gem install bundler
$ bundle -v
$ gem update bundler
$ gem uninstall bundler
Gemfile 是 Bundler(也是 gem)的配置文件,其中包含項目的 gem 列表(依賴項)
# 在項目根目錄的 Gemfile 中指定 gem
ruby '2.5.6'
source 'https://rubygems.org'
gem 'nokogiri'
gem 'rack', '~>1.1'
gem 'rspec', :require => 'spec'
安裝 Gemfile 中的所有 gem
$ bundle install
$ gem install bundler -v 1.17
$ gem install minitest -v 5.8.4
# 使用 Bundler 更新單個 gem
$ bundle update nokogiri
# 使用 Bundler 更新 Gemfile 中的每個 gem
$ bundle update
| 保留字 | 描述 |
|---|---|
__ENCODING__ | 當(dāng)前文件的腳本編碼 |
__LINE__ | 當(dāng)前文件中此關(guān)鍵字的行號 |
__FILE__ | 當(dāng)前文件的路徑 |
BEGIN | 包含在 { } 中的代碼在程序運行之前運行 |
END | 包含在 { } 中以在程序結(jié)束時運行 |
alias | 為現(xiàn)有方法、運算符、全局變量創(chuàng)建別名 |
and | 邏輯與運算符 |
begin | 開始一段代碼 |
break | 終止循環(huán) |
case | 將表達(dá)式與匹配的 when 子句進(jìn)行比較,其中 以 end 結(jié)束 |
class | 定義一個類 |
def | 定義函數(shù)/方法 |
defined? | 檢查某個變量、函數(shù)是否存在 |
do | 開始一個代碼塊并執(zhí)行塊中的代碼,以 end關(guān)鍵字結(jié)束 |
else | 如果先前的條件不成立,則執(zhí)行以下代碼 |
elsif | if 表達(dá)式的替代條件 |
end | 用于結(jié)束以 begin、class、def、do、if 等關(guān)鍵字開頭的代碼塊 |
ensure | 總是在塊終止時執(zhí)行 |
false | 邏輯布爾假值 |
for | 開始一個 for 循環(huán) |
if | 如果 if 的條件語句為 true,則執(zhí)行代碼塊 |
in | 與 for 循環(huán)一起使用 |
module | 定義一個模塊 |
next | 跳轉(zhuǎn)到循環(huán)條件評估之前的點 |
nil | 為空或無效或始終為假 |
not | 邏輯否定運算符 |
or | 邏輯或運算符 |
redo | 條件循環(huán)后跳轉(zhuǎn) |
rescue | 在引發(fā)異常后評估表達(dá)式 |
retry | ? 在救援之外調(diào)用時,重復(fù)方法調(diào)用 ? 在救援內(nèi)部調(diào)用時,跳轉(zhuǎn)到塊頂部 |
return | 從方法或代碼塊返回值 |
self | 當(dāng)前對象 |
super | 調(diào)用超類中的同名方法 |
then | 與 if、unless、when、case、rescue 一起使用的分隔符 |
true | 邏輯布爾真 |
undef | 使當(dāng)前類中的方法/函數(shù)未定義 |
until | 在條件語句為假時執(zhí)行代碼塊 |
when | 在 case 語句下開始一個子句 |
while | 執(zhí)行代碼塊,直到條件語句變?yōu)榧?/td> |
yield | 執(zhí)行傳遞給方法的代碼塊 |
# 單行注釋
=begin
多行
注釋
=end
=begin 注釋第 1 行 =end
puts "Hello world!" # 代碼的內(nèi)聯(lián)注釋
andornot&&||!&|^~<<>>+-*/%**==!=><>=<=<=>===eql?equal?# 添加
1 + 1 #=> 2
# 減法
2 - 1 #=> 1
# 乘法
2 * 2 #=> 4
# 分配
10 / 5 #=> 2
17 / 5 #=> 3, not 3.4
17 / 5.0 #=> 3.4
# 指數(shù)
2 ** 2 #=> 4
3 ** 4 #=> 81
# 模數(shù)(求除法的余數(shù))
8 % 2 #=> 0 (8 / 2 = 4; 沒有剩余)
10 % 4 #=> 2 (10 / 4 = 2 余數(shù)為 2)
a = 10
b = 20
a == b #=> false
a != b #=> true
a > b #=> false
a < b #=> true
a >= b #=> false
a <= b #=> true
# 比較運算符
a <=> b #=> -1
c = 20
c <=> b #=> 0
c <=> a #=> 1
# 用于測試 case 語句的 when 子句中的相等性
(1...10) === 5 #=> true
# 如果接收者和參數(shù)具有相同的類型和相等的值,則為真
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 并行賦值
a = 10
b = 20
c = 30
a, b, c = 10, 20, 30
# Ruby 位運算符
a = 60
b = 13
# & 如果兩個操作數(shù)中都存在,則二進(jìn)制 AND 運算符將位復(fù)制到結(jié)果中。
a & b #=> 12
# | 如果二進(jìn)制或運算符存在于任一操作數(shù)中,則復(fù)制一個位。
a | b #=> 61
# ^ 二元異或操作符如果在一個操作數(shù)中設(shè)置,則復(fù)制該位,但不能同時在兩個操作數(shù)中設(shè)置。
a ^ b #=> 49
# ~ 二進(jìn)制補(bǔ)碼運算符是一元的,具有“翻轉(zhuǎn)”位的效果。
~a
# << 二進(jìn)制左移運算符。 左操作數(shù)的值被移動
# 左操作數(shù)指定的位數(shù)。
a << 2
# >> 二進(jìn)制右移運算符。 左操作數(shù)的值被移動
# 右操作數(shù)指定的位數(shù)。
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 三元運算符
# ? :
# 如果條件為真? 然后值 X :否則值 Y
a == 10 ? puts 'Right' : puts 'Wrong'
# Ruby 范圍運算符
# .. 創(chuàng)建從起點到終點的范圍(含)
1..10 #=> 創(chuàng)建從 1 到 10 的范圍(包括 1 到 10)
# ... 創(chuàng)建一個從起點到終點的范圍,不包括在內(nèi)
1...10 #=> 創(chuàng)建一個從 1 到 10 的獨占范圍
!, ~, unary +**unary -*, /, %+, -<<, >>&^>, >=, <, <=<=>, ==, ===, !=, =~, !~&&?, :modifier-rescue=, +=, -=, *=, /=, %=definednotor, andmodifier-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] | 持續(xù)的 | PI = 3.14 | 常量變量必須初始化,您可以更改常量,但您會收到警告 |
有五種不同類型的變量。第一個字符確定范圍
current_weather = "rainy"
_weather = "sunny"
必須以下劃線或小寫字母開頭
# 實例類變量
@current_weather = "rainy"
# 全局變量
$current_weather = "rainy"
# 常量變量
WEATHER = "rainy".freeze
| 名字 | 說明 |
|---|---|
self | 當(dāng)前方法的接收者對象 |
true | TrueClass 的實例 |
false | FalseClass 的實例 |
nil | NilClass 的實例 |
__FILE__ | 當(dāng)前源文件名 |
__LINE__ | 當(dāng)前源文件的當(dāng)前行號 |
| 名字 | 說明 |
|---|---|
$-0 | $/ 的別名 |
$-a | 如果設(shè)置了選項 -a,則為真。只讀變量 |
$-d | $DEBUG 的別名 |
$-F | $; 的別名 |
$-i | 在就地編輯模式下,此變量保存擴(kuò)展,否則為零 可以指定啟用(或禁用)就地編輯模式 |
$-I | $: 的別名 |
$-l | 如果選項 -lis 設(shè)置為真。只讀變量 |
$-p | 如果選項 -pi 設(shè)置為真。只讀變量 |
$-v | $VERBOSE 的別名 |
| 名字 | 說明 |
|---|---|
$! | 異常信息消息。raise 設(shè)置此變量 |
$@ | 最后一個異常的回溯,它是 String 的數(shù)組,指示調(diào)用方法的位置。格式中的元素如:“filename:line”或“filename:line:in `methodname'”(助記符:發(fā)生異常的地方) |
$& | 與此范圍內(nèi)最后一次成功的模式匹配匹配的字符串,如果最后一次模式匹配失敗,則返回 nil。 (助記符:在某些編輯器中類似于 &)這個變量是只讀的 |
$` | 當(dāng)前范圍內(nèi)最后一次成功的模式匹配所匹配的任何內(nèi)容之前的字符串,如果最后一次模式匹配失敗,則為 nil。 (助記符:` 通常在帶引號的字符串之前)此變量是只讀的 |
$' | 當(dāng)前范圍內(nèi)最后一次成功的模式匹配所匹配的字符串后面的字符串,如果最后一次模式匹配失敗,則為 nil。 (助記符:' 通常跟在帶引號的字符串之后) |
$+ | 最后一個成功的搜索模式匹配的最后一個括號,如果最后一個模式匹配失敗,則為 nil。如果您不知道一組替代模式中的哪一個匹配,這很有用。 (助記:積極向上) |
$1, $2... | 包含上一次成功匹配的模式中相應(yīng)括號集中的子模式,不計算已經(jīng)退出的嵌套塊中匹配的模式,或者如果最后一次模式匹配失敗,則為 nil。 (助記符:如 \digit)這些變量都是只讀的 |
$~ | 當(dāng)前范圍內(nèi)最后一個匹配的信息。設(shè)置此變量會影響匹配變量,如 $&、$+、$1、$2.. 等。第 n 個子表達(dá)式可以通過 $~[nth] 檢索。 (助記符:~ 用于匹配)這個變量是局部作用域的 |
$= | 不區(qū)分大小寫的標(biāo)志,默認(rèn)為 nil。 (助記符:= 用于比較) |
$/ | 輸入記錄分隔符,默認(rèn)為換行符。像 awk 的 RS 變量一樣工作。如果設(shè)置為 nil,則將立即讀取整個文件。 (助記符:/ 用于在引用詩歌時劃定行界) |
$\ | print 和 IO#write 的輸出記錄分隔符。默認(rèn)值為無。 (助記符:它就像 /,但它是你從 Ruby 中“返回”的東西) |
$, | 打印的輸出字段分隔符。此外,它是 Array#join 的默認(rèn)分隔符。 (助記符:當(dāng)您的打印語句中有 , 時打印的內(nèi)容) |
$; | String#split 的默認(rèn)分隔符。 |
$. | 讀取的最后一個文件的當(dāng)前輸入行號。 |
$< | 由命令行參數(shù)或標(biāo)準(zhǔn)輸入給出的文件的虛擬連接文件(如果沒有提供參數(shù)文件)。 $<.file 返回當(dāng)前文件名。 (助記符:$< 是一個 shell 輸入源) |
$> | print 的默認(rèn)輸出,printf。 $stdout 默認(rèn)情況下。 (助記符:$> 用于 shell 輸出) |
$_ | 通過gets或readline輸入String的最后一行。如果gets/readline 遇到EOF,它被設(shè)置為nil。這個變量是局部作用域的。 (助記符:部分與 Perl 相同) |
$0 | 包含包含正在執(zhí)行的 Ruby 腳本的文件的名稱。在某些操作系統(tǒng)上,分配給 $0 會修改 ps(1) 程序看到的參數(shù)區(qū)域。作為一種指示當(dāng)前程序狀態(tài)的方式,這比隱藏您正在運行的程序更有用。 (助記符:與 sh 和 ksh 相同) |
$* | 為腳本提供的命令行參數(shù)。 Ruby 解釋器的選項已被刪除。 (助記符:與 sh 和 ksh 相同) |
$$ | 運行此腳本的 Ruby 的進(jìn)程號。(助記符:與貝殼相同) |
$? | 最后執(zhí)行的子進(jìn)程的狀態(tài)。 |
$: | 該數(shù)組包含通過 load 或 require 查找 Ruby 腳本和二進(jìn)制模塊的位置列表。 它最初由任何 -I 命令行開關(guān)的參數(shù)組成,然后是默認(rèn)的 Ruby 庫,probabl "/usr/local/lib/ruby",然后是 ".",表示當(dāng)前目錄 . (助記符:冒號是 PATH 環(huán)境變量的分隔符) |
$" | 該數(shù)組包含由 require 加載的模塊名稱。 用于防止 require 兩次加載模塊。助記符:防止文件被雙引號(加載) |
$DEBUG | -d 開關(guān)的狀態(tài)。 |
$FILENAME | 與$<.filename 相同 |
$LOAD_PATH | $: 的別名 |
$stdin | 當(dāng)前的標(biāo)準(zhǔn)輸入 |
$stdout | 當(dāng)前的標(biāo)準(zhǔn)輸出 |
$stderr | 當(dāng)前標(biāo)準(zhǔn)錯誤輸出 |
$VERBOSE | 詳細(xì)標(biāo)志,由 -v 開關(guān)設(shè)置到 Ruby 解釋器 |
| 名字 | 說明 |
|---|---|
TRUE | 典型的真值。在 Ruby 中,所有非 false 值(除了 nil 和 false 之外的所有值)都是 true |
FALSE | 虛假本身 |
NIL | 零本身 |
STDIN | 標(biāo)準(zhǔn)輸入。$stdin 默認(rèn)值 |
STDOUT | 標(biāo)準(zhǔn)輸出。$stdout 默認(rèn)值 |
STDERR | 標(biāo)準(zhǔn)錯誤輸出。$stderr 默認(rèn)值 |
ENV | 類哈希對象包含當(dāng)前環(huán)境變量。 在 ENV 中設(shè)置值會更改子進(jìn)程的環(huán)境 |
ARGF | $< 的別名 |
ARGV | $* 的別名 |
DATA | 腳本的文件對象,就在 END 之后。 除非未從文件中讀取腳本,否則未定義 |
VERSION | Ruby 版本字符串 |
RUBY_RELEASE_DATE | 發(fā)布日期字符串 |
RUBY_PLATFORM | 平臺標(biāo)識符 |
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 | TrueClass FalseClass |
Symbol | a = :status | a.class > Symbol | # |
Range | a = 1..3 | a.class > Range | # |
Nil | a = nil | a.class > NilClass | # |
# 兩者都是同義詞
a = 37
a.kind_of? Integer
# true
a.is_a? Integer
# true
week_days = {sunday: 11, monday: 222}
2.even?
# true
3.even?
# false
.. 用于創(chuàng)建包含范圍
range = 1..10
range.to_a
# 輸出 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
... 用于創(chuàng)建專屬范圍
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}"}
# 輸出
# 1
# 3
# 5
# 7
# 9
# 11
# 13
# 15
# 17
# 19
num = 2
puts 'two' if num == 2
如果條件為真,則執(zhí)行代碼
temp = 19
if temp >= 25
puts "hot"
elsif temp < 25 && temp >= 18
puts "normal"
else
puts "cold"
end
# 輸出 => normal
# 除非與 if 相反,當(dāng)語句為假時進(jìn)行評估
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 返回最后執(zhí)行的表達(dá)式的值
case input
# 檢查一個整數(shù),19
when 19
puts "It's 19"
# 檢查浮點數(shù),33.3
when 33.3
puts "It's 33.3"
# 檢查一個確切的字符串,“Zaman”
when "Zaman"
puts "Hi Zaman"
when 10
puts "It's 10"
# 檢查范圍
when 7..11
puts "It's between 7 and 11"
# 檢查多個值,“咖啡”
when "tea", "coffee"
puts "Happy days"
# 檢查正則表達(dá)式“aA6”
when /^a[A-Z]+[0-6]+$/
puts "It's a valid match"
# 通過與 String 類“任何字符串”
# 進(jìn)行比較來檢查任何字符串
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"
字符串插值允許您將字符串組合在一起
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"
子字符串是字符串的一小部分,如果你只想要那個特定的部分,它會很有用,比如開頭、中間或結(jié)尾
"HELLO World".downcase # "hello world"
"hello worlD".upcase # "HELLO WORLD"
"hEllo wOrlD".capitalize # "Hello world"
"hEllo WOrlD".swapcase # "HeLLO woRLd"
| 函數(shù)名稱 | Output | Note |
|---|---|---|
| length or size | "HELLO World".length => 11 "HELLO World".size => 11 | 返回字符串的長度 |
| reverse | "hello worlD".reverse => "Dlrow olleh" | 返回反轉(zhuǎn)的字符串 |
| 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" | 它將刪除(修剪)以下任何前導(dǎo)和尾隨字符: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 | 檢查字符串是否以特定前綴結(jié)尾 |
| 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"] | 將字符串轉(zhuǎn)換為字符數(shù)組 |
| join | arr = ['a', 'b', 'c'] <br> arr.join => "abc" | 將數(shù)組轉(zhuǎn)換為字符串 |
| to_i | a = "49" <br> a.to_i => 49 | 將字符串轉(zhuǎn)換為整數(shù) |
| chop | "abcd?".chop("?") => "abcd" | 從字符串中刪除最后一個字符 |
| count | str = "aaab" <br> str.count("a") 3 | 計算字符串中的字符 |
| to_f | a = "49" a.to_f 49.0 | 將字符串轉(zhuǎn)換為浮點數(shù) |
| to_sym | a = "key" a.to_sym :key | 將字符串轉(zhuǎn)換為符號 |
| match | "abcd?".match(/ab/) => #<MatchData "ab"> | 將模式轉(zhuǎn)換為正則表達(dá)式并在字符串上調(diào)用其匹配方法 |
| empty? | "hello".empty? => false | 如果字符串的長度為零,則返回 true |
| squeeze | "Booook".squeeze => "Bok" | 返回字符串的副本,其中相同字符的運行被單個字符替換 |
| * | puts "Ruby " * 4 => Ruby Ruby Ruby Ruby | 返回多個 self 副本的串聯(lián) |
| + | "sammy " + "shark" => "sammyshark" | 返回 self 和給定的其他字符串的連接 |
| eql? | s = 'foo' => true s.eql?('foo') => true | 如果對象具有相同的長度和內(nèi)容,則返回 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)
# 輸出 => 30
def method_name(parameter1, parameter2)
puts "#{parameter1} #{parameter2}"
return parameter1 + parameter2
end
# 輸出 => 30
res = method_name(parameter1, parameter2)
# 可以調(diào)用不帶括號的方法
res = method_name parameter1, parameter2
類方法是類級別的方法。 有多種定義類方法的方法
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
類方法是類對象的實例方法。 當(dāng)創(chuàng)建一個新類時,“Class”類型的對象被初始化并分配給一個全局常量(在本例中為 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)
# 輸出 => -11
# 或者您可以提供這樣的值
res = method_name("ADD", 2, 2, 2, 3, 3, 3)
# 輸出 => 15
a = ["Drama", "Mystery", "Crime",
"Sci-fi", "Disaster", "Thriller"]
a.sort
puts a
# 我們沒有修改對象
# Drama
# Mystery
# Crime
# Sci-fi
# Disaster
# Thriller
a.sort!
puts a
# 修改對象
# Crime
# Disaster
# Drama
# Mystery
# Sci-fi
# Thriller
當(dāng)您要修改對象時,在方法之后使用 !
在 ruby 中,以問號 (?) 結(jié)尾的方法稱為布爾方法,它返回 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(用于多行)或花括號 { 和 }(用于單行)之間的代碼稱為塊,它們可以在兩個管道之間定義多個參數(shù) (|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
# 塊體
# a = 10
# res = a * s
# puts res
# 塊參數(shù)
# |s|
塊可以作為方法參數(shù)傳遞,也可以與方法調(diào)用相關(guān)聯(lián)。 塊返回最后評估的語句
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" }
# 輸出
# 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}" }
# 輸出
# Big data 10 TB
# Big data 100 GB
# Big data 30 MB
give_me_data
puts "我在 give_me_data 方法里面"
end
def test
puts "我在測試方法里面"
give_me_data { return 10 } # 代碼從這里返回
puts "I am back in test method"
end
return_value = test
# 輸出
# 我在測試方法里面
# 我在 give_me_data 方法里面
# 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 就像一個可以存儲在變量中的塊
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 "我在 give_me_data 方法里面"
p = Proc.new { return 10 }
p.call # 代碼從這里返回
puts "I am back in give_me_data method"
end
return_value = give_me_data
puts return_value
# 輸出
# 我在 give_me_data 方法里面
# 10
l = lambda { puts "Hello World" }
# 速記
l = -> { puts "Hello World" }
# 調(diào)用 lambda
l.call
# 輸出 => Hello World
有多種方法可以調(diào)用 lambda
l.()
l[]
l = -> (count) { "Hello World " * count }
l.call 5
# 輸出
# "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
# 輸出 => 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"
]
# 索引 -1 表示最后一個元素
str_array[-1] #=> "array"
# 索引 -2 表示倒數(shù)第二個元素
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: 數(shù)組邊界外的索引 100:-6...6
arr.fetch(100, "oops") #=> "oops"
超出邊界,給默認(rèn)值
arr = [1, 2, 3, 4, 5, 6]
arr.first # 第一個值 => 1
arr.last # 最后一個值 => 6
# take 返回前 n 個元素
arr.take(3) #=> [1, 2, 3]
# drop 在 n 個元素被刪除之后
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]
# 或者我們可以將范圍轉(zhuǎn)換為數(shù)組
(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
# 輸出 => 8
您可以使用大小或長度,兩者都是同義詞
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
# 輸出 => 10
a = ["tom", "mot", "otm"]
b = [2, 3, 5]
a.zip(b)
# 輸出
# [["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}"
# 輸出 => [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 }
# 輸出
# ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Saturn", "Uranus", "Venus"]
planets.sort_by { |p| p.length }
# 輸出
# ["Mars", "Earth", "Venus", "Saturn", "Uranus", "Neptune", "Jupiter", "Mercury"]
primes = [7, 2, 3, 5]
primes.max_by { |p| p }
# 輸出 => 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]
# 當(dāng)你有單行塊時
salary = [399, 234, 566, 533, 233]
salary.each { |s| puts s }
# 輸出
# 399
# 234
# 566
# 533
# 233
當(dāng)你有一個多行塊時,你可以用 do 和 end 替換花括號 {}
salary.each do |s|
a = 10
res = a * s
puts res
end
# 輸出
# 3990
# 2340
# 5660
# 5330
# 2330
或者您可以使用大括號 {} 和分號作為分隔符而不是換行符來做同樣的事情
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}" }
# 輸出
# 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]
# 另一方面,每個都返回原始值
salary = [399, 234, 566, 533, 233]
salary.each { |s| s * 10 }
# 返回
# [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] }
# 輸出
{"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是不可變的,由于初始對象是0,所以方法返回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)}"}
# 輸出
# 將打印 10 個隨機(jī)數(shù)
僅僅因為你可以并不意味著你應(yīng)該像這樣迭代一個數(shù)組
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}"}
# 輸出
# 19
# 17
# 15
# 13
# 11
# 9
# 7
# 5
# 3
# 1
numbers = [2, 2, 2, 2, 2]
numbers.inject{ |res, n| res + n }
# 輸出是所有數(shù)字之和的結(jié)果
# 如果不給res設(shè)置初始值,則數(shù)組的第一個元素作為res的初始值
# 10
# 現(xiàn)在將 res 的值設(shè)置為 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(:+)
# 輸出
# 10
使用初始值和符號
numbers = [2, 2, 2, 2, 2]
numbers.inject(11, :+)
# 輸出
# 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 }
# 現(xiàn)在你有一個偶數(shù)數(shù)組
# [2, 4, 6, 8, 10]
# 如果沒有滿足您的邏輯的值,則返回一個空數(shù)組
[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 }
# 如果數(shù)字是偶數(shù)則拒絕,所以現(xiàn)在我們有一個奇數(shù)數(shù)組
# [1, 3, 5, 7, 9]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.keep_if { |n| n % 2 == 0 }
# numbers 數(shù)組僅包含偶數(shù)
# [2, 4, 6, 8, 10]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.delete_if { |n| n % 2 == 0 }
# numbers 數(shù)組僅包含奇數(shù)
# [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? | 當(dāng)您想檢查所有元素是否滿足您的條件時 |
any? | 當(dāng)您想檢查至少一項是否滿足您的條件時 |
one? | 當(dāng)您想檢查一個元素是否滿足您的要求時 |
none? | 當(dāng)您想檢查是否沒有任何項目滿足您的條件時,相反? |
empty? | 當(dāng)你想檢查對象是否為空時 |
include? | 當(dāng)你想檢查元素是否存在于對象中時 |
[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
& 返回一個新數(shù)組,其中包含在數(shù)組和數(shù)組 other_array 中找到的每個元素;省略重復(fù);使用 eql? 比較項目intersection 返回一個新數(shù)組,其中包含在 self 和所有給定數(shù)組 other_arrays 中找到的每個元素;省略重復(fù);使用 eql? 比較項目+ 返回一個數(shù)組,該數(shù)組包含 self 的所有元素,后跟給定數(shù)組的所有元素- 返回一個數(shù)組,其中包含在給定數(shù)組中找不到的所有 self 元素union 返回一個數(shù)組,其中包含 self 的所有元素和給定數(shù)組的所有元素,已刪除重復(fù)項difference 返回一個數(shù)組,其中包含在任何給定數(shù)組中找不到的所有 self 元素product 返回或產(chǎn)生來自 self 和給定數(shù)組的所有元素組合[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
# 輸出
# 399
# 234
通過使用 break 關(guān)鍵字
salary = [399, 234, 566, 533, 233]
salary.each do |s|
next if s == 533
puts s
end
# 輸出
# 399
# 234
# 566
# 233
通過使用 next 關(guān)鍵字
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
# 使用 < 符號從父類繼承方法和屬性
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
如果對象是給定類的實例,而不是子類或超類,則返回 true
puts (String.methods).sort
# 排除從 Object 類繼承的方法
puts (String.methods - Object.public_instance_methods).sort
String.respond_to?(:prepend)
true
String.respond_to?(:append)
false
感谢您访问我们的网站,您可能还对以下资源感兴趣:
国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片