Ruby 10 Minutes (摘要自---Ruby 用戶指南)
======類
簡單類
ruby> class Mammal
| def initialize
| end
| def breathe
| print "inhale and exhale\n"
| end
| end
nil
繼承,用<
ruby> class Cat<Mammal
| def speak
| print "Meow\n"
| end
| end
創建對象
ruby> pochi = Cat.new
#<Cat:0xbcb90>
調用方法
ruby> pochi.speak
Bow Wow
nil
成員變量
全局變量 $
實變量 @
局部變量 小寫或者_ 打頭
常量 大寫字母開頭
存取器
Shortcut縮寫 Effect等同於
attr_reader :v def v; @v; end
attr_writer :v def v=(value); @v=value; end
attr_accessor :v attr_reader :v; attr_writer :v
attr_accessor :v, :w attr_accessor :v; attr_accessor :w
======方法
參數應在一對括號內
object.method(arg1, arg2)
括號可以省掉.
object.method arg1, arg2
特殊變量self;
self.method_name(args...)
和這一樣
method_name(args...)
特殊成員方法inspect方法,類似C#的ToString
ruby> class Fruit
| def inspect
| "a fruit of the " + @kind + " variety"
| end
| end
nil
ruby> f2
"a fruit of the banana variety"
構造方法initialize,用super調用父類
ruby> class Cat<Mammal
| def initialize
| super
| print "Meow\n"
| end
| end
=====Cool 迭代之yield,retry
yield 讓流程可以使用Block
ruby> def repeat(num)
| while num > 0
| yield
| num -= 1
| end
| end
nil
ruby> repeat(3) { print "foo\n" }
foo
foo
foo
nil
案例:有while相同作用的迭代器
ruby> def WHILE(cond)
| return if not cond
| yield
| retry
| end
nil
ruby> i=0; WHILE(i<3) { print i; i+=1 }
012 nil
retry語句從頭執行迭代.這是一個死循環,到2就重新執行
ruby> for i in 0..4
| print i
| if i == 2 then
| retry
| end
| end;
===== 迭代
字符串迭代
each_byte
> "abc".each_byte{|c| printf "%c", c}
abc
each_line.
ruby> "a\nb\nc".each_line{|l| print l}
a
b
c
=====數組
定義數組:方括號裏列出元素,不限定類型
ruby> ary = [1, 2, "3"]
[1, 2, "3"]
數組加
ruby> ary + ["foo", "bar"]
[1, 2, "3", "foo", "bar"]
數組乘
ruby> ary * 2
[1, 2, "3", 1, 2, "3"]
訪問
ruby> ary[0]
1
ruby> ary[0..1]
[1, 2]
ruby> ary[-2]
2
數組字符串轉換
ruby> str = ary.join(":")
"1:2:3"
ruby> str.split(":")
["1", "2", "3"]
=============哈希表
定義
ruby> h = {1 => 2, "2" => "4"}
{1=>2, "2"=>"4"}
使用
ruby> h[1]
2
ruby> h["2"]
"4"
ruby> h[5]
nil
ruby> h[5] = 10 # appending value
10
ruby> h
{5=>10, 1=>2, "2"=>"4"}
刪除
ruby> h.delete 1 # deleting value
2
==============字符串
單引號,雙引號都可以做字符串定界符
> "abc"
> 'abc'
字符串可以跨行
"foo
bar"
雙引號的字符串允許字符轉義(Escape),用#{}內嵌表達式.
>"\n"
>"name="1000copy"
> #{name}"
單引號字符串保持原字符串
ruby> print 'a\nb\n'
a\nb\nc
字符串乘
> "foo" * 2
"foofoo"
抽取字符,返回ASCII
ruby> word[0]
102 # 102 is ASCII code of `f'
ruby> word[-1]
111 # 111 is ASCII code of `o'
提取子串:
ruby> herb = "parsley"
"parsley"
ruby> herb[0,1]
"p"
ruby> herb[-2,2]
"ey"
檢查相等:
ruby> "foo" == "foo"
true
正則表達式
// 表達爲regexp
/\w/ 字母或數字
/\s/ 非空
optimize my sight——from Refactor to DB Turning
Blog :http://1000copy.iteye.com
MicroBlog : t.sina.com.cn/1000copy
club page :http://www.cdsoftwareclub.com
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.