Ruby 讀書

輸出:前端

print java

printf 既定格式輸出正則表達式

puts 自動換行api

p 顯示對象數組

sprintf 不規則字符串ruby

pp  須要導入庫app

putc(字母)less

轉移字符和單雙引號函數

include Math或者直接Math.方法oop

變量

註釋

單行#

多行#=begin  #=end

控制結構

條件:if、unless、case

if 條件 [then]

   動做 

else

   動做

end

循環:

while 條件 do 

     動做

end

次數.times{動做}

定義方法

def  方法名

  動做

end

引用庫

require "庫名/文件名"

命令行輸入

ARGV 數組

read 須要分配文件大小的存儲空間

gets 一行空間

ruby simple_grep.rb  樣式  文件名

================================

數組

數組名=[]

數組名[索引]獲取對象

數組名[索引]=存放對象

數組沒有數據類型的限制能夠存聽任何對象

數組名.size獲取數組大小

數組.each{|變量|動做}進行遍歷

雜湊/哈希表

雜湊={key=>value的形式存放}

雜湊[鍵]=存放對象

雜湊.each{|鍵的變量,值的變量|動做}

redirect 重定向存放執行結果到文件

=================================

對象

數值對象 Numberic

字符串對象 Sring

正則表達式對象 Regexp

時間對象 

文件對象 File

目錄對象

數值、雜湊對象 Array/Hash

變量

局部變量 小寫字母或_開始

全局變量 $開始

實例變量 @起始

類變量 @@起始

虛擬變量 true/false/self

常數 全大寫

str1.equal?(str2) 判斷是否是同一對象

值同不等於對象相同

==/eql? 通過必要的變換/不通過變換 

1.0==1 #=>true 

1.0.eql?(1) #=>false

書寫易讀性建議

換行和分號、縮進、空白

================================

條件判斷

判斷結果 true/false

str.empty? 長度等於0爲true不然false

nil 也是一種假

邏輯運算

&&、||、!  /and、or、not

if 條件 [then]

   語句1

elsif 條件 [then]

   語句2

end

unless 條件 [then] 不知足條件

  語句

else

   語句

end

case 比較的對象   --相似switch的功能

when 值 [then]

  語句

when 值 [then]

  語句

when 值 [then]

   語句

else

  語句

end

=== 判斷值相等

================================

循環

times

次數.times do/{ 動做} /end  兩種樣式

for

for 變量 in 開始值..結束值 [do]

動做

end

for  變量 in 對象 [do]

  動做

end

while

while 條件 [do]

動做

end

until 否認的判斷

until 條件 [do]

動做

end 

each 遍歷

對象.each do |變量| 動做 end

對象.each {|對象| 動做}

loop{動做}不停循環 配合break中止

break中止,跳出當前循環

next 直接跳到下一次循環

redo 以相同條件從新進行這一次循環

================================

方法

實例方法

類方法

函數性方法

定義方法

def 方法名(參數1,參數2...)

  動做

end

參數接受預設值 name="king"

def hello (name="king")

puts("hello " name)

end

hello() hello king

hello("long") hello long

return 返回值,return可省略返回最後一個計算值

省略return 的實參時,則會返回nil

================================

類與模塊

對象.instance_of?  判斷對象是不是類的實例

繼承

對象.is_a?(父類) 是否繼承與

class 類名大寫開頭

類定義

end

initalize()  初始化方法

以@開頭的爲實例變量

attr_reader:name方法 只讀

attr_Write:name方法  只寫

attr_accessor:name方法

def 類名.方法名 end

class<<類名 def 方法名 end end

class 類名 def self .方法名 end end

類名.方法/類名::方法同義

以::鏈接類和常數

class 類

  PI="3.14"

end

print  類::PI

擴充類

self.

繼承

class 類名 < 父類

  類定義

end

super(父類方法)

限制方法的調用

public 

private 內部使用

protected 內部使用/同一個類

使用方法

public : 方法名

public  沒有實參即下面全部方法都是public

initialize 恆爲private

==============================

模塊 不能該建立實例 不能繼承

FileText.exist?("路徑") 文件是否存在

FileText.size("路徑") 文件大小

Mix-in 將模塊混進類裏

自定義模塊

module 模塊名

  定義

end

module_function:hello   #將hello方法以模塊函數形式公開

模塊函數內應用self,能夠取得模塊自己

===================================

錯誤處理

數據錯誤

系統錯誤

程序錯誤

忽略錯誤並繼續執行

恢復到錯誤發生前的狀態

重試

結束程序

begin 

  有可能例外的動做

rescue =>存放例外變量

  例外處理

ensure

  老是執行

end

$! 最後發生的例外

$@ 最後例外發生的位置和信息

class 例外類

message 例外消息

backtrace 例外發生位置 $@等同於$.backtrace

sub()第一個

gsub()所有

scan 只獲取不替換

retry  重試

當例外處理的begin~end 範圍就是整個飛自己時,能夠省略begin很end

捕獲指定例外 rescue Errno::ENOENT,Errno::EACCES

自定義例外類要繼承StandardError

引起例外

raise 消息

raise 例外類

raise 例外類,消息

raise

chatch 和 throw 

throw :test

catch(:test)

==================================================

數字類

數值  整數  整數/大整數

        浮點數

0123/0d123/0x123/0B110101           進制

?字符                 獲得字符的ASCII碼

** 冪 5**2     25

divmod/remainder  取整/取餘

Infinity 無限大

NaN  非數值

Math 數學模塊

數值轉換

to_f   轉換爲Float

to_i  轉換Int

返回比接收者大的最小整數ceil方法/比你接收者小的的最大整數floor方法

數數

n.times{|i|...}

form.upto(to){|i|...}  從from書到to累加

from.downto(to){|i|...}  累減

from.step(to,step){|i|...} 從from開始。每次加step,直到to爲止

=============================================================

數組

Array.new

Array.new(5)  5個nil

Array.new(5,0)  5個0

元素是字符串且不含空白式用%w 創建數組

to_a() 轉換爲數組

字符串分隔 split()

獲取數組

a[n]

a[n...m]

a[n,len]

數組.values_at(n1,n2...) 抽取想要的元素組成新數組

數組交集 arry1 & arry2

數組並集 arry1 | arry2

數組差集 arry1 - arry2

數組前段末端操做

加入 unshift   push  

取出 shift    pop

讀取 first  last

a<<item  和a.push(item) 

a.concat(b)/a+b

!對方法具備破壞性

刪除

a.compact 刪除 nil 從新組成數組  新建對象

a.compact!  返回對象a

a.delete(x) 刪除元素

a.delete_at(x) 刪除索引

測試元素,條件爲真則刪除

a.delete_if{|item|...}  破壞性

a.reject{|item|...}  沒有符合刪除條件返回nil

a.reject!{|item|...}  破壞性

取出部分並替換

a.slice!(n)

a.slice!(n..m) 

a.slince!(n,len) 

刪除重複

a.uniq

a.uniq!破壞性

--存在對應的!破壞性方法

a.clooect{|item|...}

a.map{|item|...}

a.flatten 將 嵌套的元素展開

a.reverse 反轉

a.sort

a.sort{|i,j|...}

--

a.fill(value)

a.fill(value,begin)  --從begin開始

a.fill(vlue,begin,len) --begin開始len個

a.fill(value,n..m)

a.sort_by{|i|...}

each_with_index 的到元素和索引

多維數組/矩陣

===============================

String 類

變量="***"

#{} 執行ruby語句

轉移字符

%Q 、%q 使單雙引號原樣輸出

嵌入文檔

message<<"結束記號"

   可內嵌的字符串

結束標記

字符串長度 lenght / size

empty?檢查字符串長度爲0?

unpack / pack 數組從二進制轉換爲數組/數組轉換爲二進制

指定最後一欄的字數時,能夠不用指定數值,而已*指定,意味知道字符串尾端的全部文字

big5 漢字2個字節 utf-8 3個字節

刪除換行字符的方法

必須刪除一個字符 chop

只刪除換行字符 chomp

上面兩個具備破壞性方法

while line=gets

   line.chomp!

     處理line內容

end

字符串的查找替換

index("**")左側開始

rindex("**")右側開始

inclue?("**")包含

Enumerable 模塊

s.strip去除空白

--大小寫

s.upcase

s.downcase

s.swapcase

s.capitalize

s.tr 取代替換

以上都有破壞性方法

==============================

雜湊/哈希表

Hash.new

設置值 store 

獲取值 fetch

直接取出鍵值對

取出鍵 數組方式 keys   迭代方式 each_key{|key|...}

取出值 values   each.key{|val|...}

取出鍵值對 to_a  each_key{|key,val|...}each_key{|pair|...}

查詢雜湊存在鍵或者值

h.key?(key)

h.has_key?(key)

h.include?(key)

h.member?(key)

h.value?(value)

h.has_value?(value)

length / size 雜湊大小

h.clear  清空雜湊

<=> 比較運算符  < 負值 = 爲0  >正值

===============================

正則表達式

Regexp.new("**")

%r(樣式)

%r<樣式>

%r|樣式|

%r!樣式!

正則表達式=~字符串

if 正則表達式 =~ 字符串

    成功動做

else

    失敗動做

end

...... 任何一個字符

quote  忽略全部轉義字符

i 忽略大小寫

s、e、u、n 指定字符編碼方式

x 忽略空白,並忽略#後面的內容

m 讓. 能與換行符號匹配成功

===============================

IO 類

輸入 STDIN    $stdin  

輸出 STDOUT $stdout  

錯誤輸出 STDERR $stderr

tty?

io = open (文件名,模式)

io = File.open(文件名,模式)

io.close

io.close?

require "open-uri"  通訊時管道和Socket

require "stringio"

輸入

io.gets(rs)

io.each(rs)

io.readlines(rs)

chomp!刪除行尾換行字符

io.eof?讀到盡頭

io.lineo

io.lineo=(number)

io.getc      讀取字節

io.each_byte

io.ungetc(ch)  

io.read(size)

io.write(str)

文件指針

io.pos

io.pose=(position)

io.seek(offset , whence)

IO::SEEK_SET  文件指針移動到offset所指位置

IO::SEEK_CUR  從當前算起想對位置offset處

IO::SEEK_END  從文件尾算起相對位置offset處

io.rewind  文件指針移回文件最前端

lineo 方法返回行號也歸0

io.truncate(size)  文件長度分割到實參size指定的位置

緩衝

io.flush  強制輸出緩衝區裏的數據

io.sync

io.sync=(true/false)  能夠要求全部緩衝區的寫入直接調用flush

與指令交換數據

IO.popen(command,mode)

IO.open("**",mode)

=============================

File  Dir 類

File.rename("before","after") 重命名

require "fileutils"  --複製和移動到新位置

FileUtils.cp("文件","新路徑")

FileUtils.mv("文件","新路徑")

File.delete("**")

Dir.pwd

Dir.chdir

Dir.open("**")

dir.read

[dir.close]

.  當前

..  上層

;

Dir.glob  使用萬能字符獲取目錄文件名

創建刪除目錄

Dir.mkdir("**")

Dir.rmdir("**")

文件與目錄的屬性

File.stat 獲取文件或目錄的屬性

untitle

untitle

File.utime(atime,mtime,path)

File.chmod(mode,path)

File.chown(onwer,group,path) 更改文件全部者

FileTest 模塊

untitle

文件名操做

File.basename(path[,suffix])

File.dirname(path)

File.extname(path)

File.split(path)

File.join(dir,base)

File.expand_path(path[,default_dir])

與文件操做相關的程序庫

find模塊

Find.find(dir){|path|...}

Find.prune

tempfile 模塊管理暫存文件

tempfile.new(basename[,tempdir])

tempfile.close(real)

tempfile.open

tempfile.path  返回暫存文件路徑

fileuntils 模塊

FileUtils.cp(from,to)

FileUtils.cp_r(from,to)

FileUtils.cp_rf(from,to)

FileUtils.mv(from,to)

FileUtils.rm(path) 刪除path

FileUtils.rm_r(path)

FileUtils.rm_rf(path)

FileUtils.compare(from,to) 比較文件相同爲true

FileUtils.install(from,to[,option])  文件複製到to

FileUtils.mkdir_p(path)

==============================

Time Date 類

Time Date DateTime

untitle

時間格式

Time#strftime(format)

untitle

本地時間

Time#localtime

t=Time.now

t.utc

t.localtime

Time.parse

require "date"

untitle

to_time

DateTime與Time差別

DateTime類繼承Date 基本單位是 日

offset 時差處理

計算不到1天的差別使用Rational對象

Rational(分子,分母)

Date.today

>> << 獲取幾個月後或前的同一天

Date.parse 

===============================

字符串

string="hello"

string.length    統計字符串長度 5

string.length()

string.size

string.count 'l'  統計字母個數

string.count('l')

string.length.next   6

單引號

puts 'may\nbut dosn\'t'  --may but dosn't

初始化另外一種方法

untitle

string.silce(3,5)  截取從0開始

string[3,5] 

string[index].chr  獲取單個字符

string.empty? 是否爲空

string.include? 'h' 是否包含

str<<'a'+'b'

str<<#{val1}  #{val2}

str<< val1<<' '<<val2

Array#join 在數組每一個元素之間插入分隔字符串

data=[1,2,3]

s=' '

data.each{|x| s<<x<<' and a '}

s   "1 and a 2 and a 3 and a "

data.join(' and a')   "1 and a 2 and a 3" 忽略最後的分隔符

data.each_with_index{|x,i| s<<x; s<<"|" if i<data.lenght-1 }  1|2|3

num=5

"this is #{num}"  this is 5

#{文本表達式}

要避免字符串插入,可轉義字符或者將字符串轉入單引號

here document結構

自定義結束的字符

email=<<END

遇到END即結束

變量帶入現有字符串

temp='this is %s'

temp % 'money'   --this is money

ERB模板

require 'erb'

temp=ERB.new %q{chunky <%=food %>}

food='ocean'

temp.result(binding)  --chunky ocean

eval(%{''#(self)''},binding)

l

反轉字符串

string.reverse

split 分隔符

?A  --65  獲取十進制數據

?\C-a  --1

特殊符號只在雙引號、%{}、% Q{}中進行解釋

單引號和%q{}不能解釋

"this\tis" this is 

'this\tsi' this\tis

字符串和值的相互轉化

?a   --97

'a'[0] --97

'yuan'[2]  --97

97.chr --"a"

字符串與符號之間的轉化

.to_s  

.id2name

.intern

.intern.object_id

處理字符串中每一個字符

'hello'.each_byte{|x| puts 「#{x}=#{x.chr}」}

'hello'.scan(/./){|x| puts x}

處理字符串中的每一個字

.scan(/\w+([-'.]\w+)/){處理}

.word-count

大小寫轉換

.upcase/downcase

.swapcase 大寫變小寫,小寫變大寫

.capitalize  字符串單元格字母大寫

.tr('須要替換','替換文本')

空白

.strip 去除空白

.ljust/rjust/center  去除左右中的空白/添加空白

.gsub("\t","  ")  正則去除

.to_str 是不是字符串

.slice(*,*) 起始/長度 從0開始

.[*,*]  數字/正則

$KCODE='u'

require 'jcode'

==============================================

.to_i [(進制)] 不能轉換返回0

.to_f

.hex   --八進制

.oct   --十六進制

Integer('須要轉換的')

Float('須要轉換的')

.scanf()

.approx()

Float::EPSILON

.to_s

BigDecimal()

BigDecimal().precs --檢查數值精度

BigMath 

.sqrt

.round

mathn

rand 

.collect

.inject

.reduce(*)

modes   --數組中重複項

Rational    a/b b>0

mean  --平均值

median --中值 非最大非最小

mean_and_standard_deviation  --平均值和偏移量

.between?(*,*)

sub(*,*)

gsub(*,*)

/^  $/

untitle

=~ 

.match

.join

.split

.inspect

------------------------------

.each

.collect

.empty?

.include?

.first 

.last

.reverse

.size

.keys

.delete

.delete_if

case  *

when *

   *

when *

   *

else

end

if/unless

while/until

yield

lambda

Time.now

.local

.gm

.utc

untitle

Fixnum

Bignum

.to_a  --數組

(*...*) 範圍

.to_sys

word_count

paragraph_count

sentence_count

%w{ }

====================================================================

換行  \n    跨行 \

Numeric  

String

Array

Hash

Regexp

File

true/false/self

untitle

.object_id  惟一編號

.equal?(*) 對象相等

== /eql?值相等

::  --調用常數

pack/unpack   --數組對象轉換成二進制數據

指定最後一欄的字數時,能夠不用指定數值,以*代替待字符串尾端的全部文字

chop 刪除最後一個字符

chomp 刪除行尾換行符

index/rindex --定位

include?()--包含

upcase/downcase  --大小寫

swapcase --大小寫轉換

capticalize  --首字母大寫

store

fetch  取值是不存在的話會報錯 第二個參數具備優先值

each_key /each_value

reject 和 delete_if 

<< / <<-

.clear

Regexp.quote()  忽略轉義字符

i 忽略大小寫

s、e、u、n  指定編碼方式

x 忽略空白

m 讓.與換行符匹配

eof? 

lineno

getc/each_byte/ungetc

pos/seek/rewind/truncate

flush

sync

Dir.glob

mkdir/rmdir 建立和刪除目錄

File.basename

File.dirname

File.extname

File.split

File.join(dir,base)

File.expand_path

File.find

File.prune

tempfile.new

.close

.open

.path

FileUtils.cp

.cp_r

.cp_rf

.mv

.rm

.rm_r

.rm_rf

.compare

.install

.mkdir_p

=====================================================

.parse

.isdst 夏令時

.step(*)  步長

(0..20).step(3){|x| print x }

Arry.uniq --去除重複元素

to_set

.all?

.any?

.chunk

.even?

.count(*)

.cycle(num)

.delete(*)

File.foreach

.collect

.delete

.drop(*) 

.drop_while

each_cons(*)

.detect

.flat_map

.find

.select

.first

.grep

.group_by

.menber?()

.include?()

.minmax  

none?

parition

.regect

.take()

.entries

compact

.insert(*,*)

.assoc(*)

.at(num)

.combination(num)

.compact(*)

.concat(*)

.cycle(num)

.delete_at(num)

.fetch(num)

.fill(*)

.index(*)

.flatten(num)

.forzen?

.replace(*)

.inspect

.join

.keep_if

.permutation(num)

.pop(num)

.product(*)

.push(*)

.rassoc(*)

.repeated_combination(num)

.repeated_permutation(num)

.reverse_each

.rindex(*)

.rotate(num)

.sample(num)

.shift(*)

.shuffle(num)

.transpose

.uniq

.values_at

======================================================================

irb(main):004:0> 3 + 4 => 7 irb(main):005:0> 3 * 4 => 12 irb(main):006:0> 3 - 4 => -1 irb(main):007:0> 3 / 4 => 0 irb(main):008:0> 3.0 / 4.0 => 0.75 irb(main):009:0> 0xF => 15 irb(main):010:0> 0x3 * 0xA => 30

irb(main):011:0> 14.to_s => "14"

irb(main):012:0> "hello" + "there" => "hellothere" irb(main):013:0> "Reader".length => 6 irb(main):014:0> "Reader".reverse => "redaeR" irb(main):015:0> "reader".capitalize => "Reader" irb(main):016:0> "Reader".include?("foo") => false irb(main):017:0> "Reader".include?("ade") => true irb(main):018:0> " Reader ".strip => "Reader" irb(main):019:0> "Reader".gsub("e", "f") => "Rfadfr" irb(main):020:0> "Reader".delete("ea") => "Rdr" irb(main):021:0> "a" < "b" => true

irb(main):022:0> "Bob".between? "Adam", "Chris" => true

irb(main):023:0> "hi" * 5 => "hihihihihi"

irb(main):024:0> "Reader".crypt("ab") => "abofgDjq6JNJo"

irb(main):025:0> "Reader"[2] => 97 irb(main):026:0> ?a => 97 irb(main):027:0> 97.chr => "a"

irb(main):028:0>x = 42 =>42

irb(main):029:0> "The answer is #{x}!" => "The answer is 42!" irb(main):030:0> "The answer is #{6 * 7}!" => "The answer is 42!"

irb(main):031:0> 'The answer is #{x}!' => "The answer is \#{x}!"

irb(main):032:0> a = ["hello", 42, "world"] => ["hello", 42, "world"] irb(main):033:0> a << 5.0 * 7.5 => ["hello", 42, "world", 37.5] irb(main):034:0> a[0] => "hello" irb(main):035:0> a[6] = 'hi' * 2 => "hihi" irb(main):036:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):037:0> a[99] => nil

irb(main):044:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):045:0> a.compact => ["hello", 42, "world", 37.5, "hihi"] irb(main):046:0> a.join => "hello42world37.5hihi" irb(main):047:0> [10, 75, 6, 29].sort => [6, 10, 29, 75] irb(main):048:0> [[1, 2, 3], [4, 5, 6]] => [[1, 2, 3], [4, 5, 6]] irb(main):049:0> [[1, 2, 3], [4, 5, 6]].flatten => [1, 2, 3, 4, 5, 6]

irb(main):050:0> h = {:foo=>'bar', :baz=>'biff'} => {:foo=>"bar", :baz=>"biff"} irb(main):051:0> h[:foo] => "bar" irb(main):052:0> h[:unknown] => nil irb(main):053:0> h[:baz] = "new" => "new" => {:foo=>"bar", :baz=>"new"} irb(main):054:0> h.entries => [[:foo, "bar"], [:baz, "new"]]

5.class => Fixnum (2 ** 96).class => Bignum 7.5.class => Float (1..10).class => Range "foo".class => String /^foo[a-e]$/.class => Regexp :foo.class => Symbol [].class => Array {}.class => Hash

irb(main):001:0> h = {:foo=>'bar', :hi=>'there'} => {:foo=>"bar", :hi=>"there"} irb(main):002:0> h.each_key {|k| puts k} foo hi => {:foo=>"bar", :hi=>"there"} irb(main):003:0> h.each {|k,v| puts "#{k}: #{v}"} foo: bar hi: there => {:foo=>"bar", :hi=>"there"}

irb(main):004:0> n = [5, 6, 10] => [5, 6, 10] irb(main):005:0> t = 1 => 1 irb(main):006:0> n.each { |i| t *= i } => [5, 6, 10] irb(main):007:0> t => 300

irb(main):008:0> t = 1 => 1 irb(main):009:0> f = lambda { |i| t *= i } => #

irb(main):001:0> def greet(name) irb(main):002:1> puts "Hello, #{name}!" irb(main):003:1> end => nil irb(main):004:0> greet "Reader" Hello, Reader! => nil irb(main):005:0> greet 42 Hello, 42! => nil

irb(main):006:0> def print_len(item)

irb(main):007:1> puts "Len = #{item.length}"

irb(main):008:1> end

=> nil

irb(main):009:0> print_len "Reader"

Len = 6

=> nil

irb(main):010:0> print_len [1, 4, 9]

Len = 3

=> nil

irb(main):011:0> print_len 42

NoMethodError: undefined method <span class="pf">'

</span>length' for

42:Fixnum

from (irb):7:in <span class="pf">'</span>print_len'

from (irb):11

irb(main):012:0>def repeat(val, times = 5) irb(main):013:1>val.to_s * times irb(main):014:1>end =>nil irb(main):015:0>repeat "hi" =>"hihihihihi" irb(main):016:0>repeat "hi", 3 =>"hihihi" irb(main):017:0>repeat 10, 3 =>"101010"

irb(main):018:0> def add(*values) irb(main):019:1> result = 0 irb(main):020:1> values.each {|x| result += x} irb(main):021:1> result irb(main):022:1> end => nil irb(main):023:0> add 1, 2, 3, 4, 5 => 15

irb(main):001:0> class Manners irb(main):002:1> def greet(name) irb(main):003:2> puts "Hello, #{name}!" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> m = Manners.new => #

irb(main):008:0> m.farewell "Reader" NoMethodError: undefined method 'farewell' for #<Manners:0x404839c> from (irb):8

irb(main):009:0>class Manners irb(main):010:1>def farewell(name) irb(main):011:2>puts "Goodbye, #{name}!" irb(main):012:2>end irb(main):013:1>end =>nil irb(main):014:0>m.farewell "Reader" Goodbye, Reader! =>nil

irb(main):001:0> class Manners irb(main):002:1> def initialize(name) irb(main):003:2> @name = name irb(main):004:2> end irb(main):005:1> def greet irb(main):006:2> puts "Hello, #{@name}!" irb(main):007:2> end irb(main):008:1> def farewell irb(main):009:2> puts "Goodbye, #{@name}!" irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> m = Manners.new "Reader" => #

irb(main):001:0> class Array irb(main):002:1> def print_tr irb(main):003:2> puts "<tr>" irb(main):004:2> each { |item| irb(main):005:3* puts " <td>#{item}</td>" irb(main):006:3> } irb(main):007:2> puts "</tr>" irb(main):008:2> end irb(main):009:1> end => nil Irb(main):010:0> ["hello","world!"].print_tr <tr> <td>hello</td> <td>world!</td> </tr> => nil

irb(main):001:0> def String.concat(s1, s2) irb(main):002:1> s1 + ' ' + s2 irb(main):003:1> end => nil irb(main):004:0> String.concat 'hi', 'bye' => "hi bye"

irb(main):001:0> class String irb(main):002:1> def self.concat(s1, s2) irb(main):003:2> s1 + ' ' + s2 irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> String.concat 'hi', 'bye' => "hi bye"

irb(main):001:0> o = Object.new => #<Object:0x3f8feb4> irb(main):002:0> o.methods => ["inspect", "taguri", "clone", "public_methods" , "taguri=", "display", "instance_variable_defined ?", "equal?", "freeze", "methods", "respond_to?", ...many more methods listed...

irb(main):003:0> o.inspect => "#<Object:0x3f8feb4>" irb(main):004:0> o.send "inspect" => "#<Object:0x3f8feb4>"

irb(main):139:0> class Object irb(main):140:1> def method_missing(*args) irb(main):142:2> puts args irb(main):143:2> end irb(main):144:1> end => nil irb(main):145:0> o.foobar 1, 2, 3 foobar 1 2 3 => nil

def method_missing(method, *args)

irb(main):001:0> class Person irb(main):002:1> def age irb(main):003:2> @age irb(main):004:2> end irb(main):005:1> def age=(value) irb(main):006:2> @age = value irb(main):007:2> end irb(main):008:1> end => nil

irb(main):009:0>p = Person.new =>#

class Person prop :age end

irb(main):001:0> class Object irb(main):002:1> def self.prop *names irb(main):003:2> names.each { |name| irb(main):004:3* self.class_eval " irb(main):005:3" def #{name} irb(main):006:3" @#{name} irb(main):007:3" end" irb(main):008:3> self.class_eval " irb(main):009:3" def #{name}=(value) irb(main):010:3" @#{name} = value irb(main):011:3" end" irb(main):012:3> } irb(main):013:2> nil irb(main):014:2> end irb(main):015:1> end => nil

irb(main):016:0> class Person irb(main):017:1> prop :age, :name irb(main):018:1> irb(main):019:1* def initialize(age, name) irb(main):020:2> @age = age irb(main):021:2> @name = name irb(main):022:2> end irb(main):023:1> end => nil irb(main):024:0> p = Person.new(36, "Brad") => #

1)Ruby區分大小寫

2)# 後跟單行註釋

3)=begin 和 =end 以前的是多行註釋:

=begin   

  這之間是多行註釋

  也是Ruby的內嵌文檔(Rdoc)註釋,

  相似javadoc,能夠用命令ri從源文件生產文檔。   

=end  

4)分隔符

; - 分號用來分隔一行中的多個語句

() - 圓括號提升優先級,定義方法時容納參數列表

空格 - 分隔字符,在可省略()的地方代替()

, - 逗號隔開多個參數

.  - 點將對象與它的方法隔開

:: - 雙冒號域做用符,將模塊(類)與它的常量隔開

5)關鍵字

模塊定義:module

類定義: class

方法定義:def,undef

檢查類型:defined?

條件語句:if,then,else,elsif,case,when,unless

循環語句:for,in,while,until,next,break,do,redo,retry,yield

邏輯判斷:not,and,or

邏輯值: true,false

空值:  nil  

異常處理:rescue,ensure  

對象引用:super,self  

塊的起始:begin/end

嵌入模塊:BEGIN,END  

文件相關:FILE,LINE

方法返回:return

別名:  alias

6)運算符(優先級由高到低)

[]、[]=

數組下標、給數組元素賦值

**

乘冥

!、~、+、-

非、位非、一元加(正號)、負號

*、/、%

乘、除、模

+、-

加、減

>>、<<

移位:右移、左移

&

位與

^、|

位異或、位或

<=、<、>、>=

小於等於、小於、大於、大於等於

<=>、==、===、=~、!=、!~

各類相等判斷(不能重寫=~、!=、!~)

&&

短路與

||

短路或

..、...

區間的開始點到結束點

? :

三元條件運算符

=、%=、~=、/=、-=、+=、|=、&=、>>=、<<=、*=、&&=、||=、**=

各類賦值

defined?

檢查類型

not

邏輯非

or、and

邏輯或、邏輯與

if、unless、while、until

判斷與循環

begin、end

定義方法,類,模塊的範圍

ruby中沒有"++"、"--"一類的運算符,但能夠經過"+=1"、"-=1"實現

7)命名規則

Ruby 的標識符用來指向常量,變量,方法,類和模塊。

Ruby的標識符區分大小寫。

關鍵字不能用來看成常量,變量,方法,類或模塊的名字。

標識符的首字符用來幫助咱們肯定標識所指向內容的做用域。

Ruby 使用一個約定來幫助它區別一個名字的用法:名字前面的第一個字符代表這個名字的用法:

  局部變量、方法參數和方法名稱應該用一個小寫字母開頭或者用一個下劃線開頭;

  全局變量用美圓符做爲前綴「$」;

  而實例變量用「@」開頭;

  類變量用「@@」 開頭;

  類名、模塊名和常量應該用大寫字母開頭。

詞首字母后面能夠是字母、數字和下劃線的任意組合;「@」後面不能夠直接跟數字。

Ruby  程序代碼如今是用7位ACSII碼來表示,經過語言擴展來支持UTF8等8位編碼系統。

Ruby 2.0  版本將使用 16位的 Unicode  編碼。

相關文章
相關標籤/搜索