ruby基礎用法簡單整理

ruby基礎用法簡單整理

基礎變量部分

  1. 變量聲明
a = 10  a = "string"
  1. 支持并行賦值
a,b = 3,5   a,b = 3, "5"
a = b = 3
  1. 變量操作
a += 1
 沒有++操作符號
  1. 變量交換
a,b = 3,5
a,b = b,a     #=> 5,3
  1. 語句后面不跟";"
a = 10
 -5 / 2           #=> -3
 -5.0/ 2          #=> -2.5
-5 % 2      #=> 1
-5 % 2.2    #=> 1.6

字符串

  1. 聲明
str = "string"
  1. 切片操作
 str[1...3] #=> "tr"
 str[1,3] #=> "tri"
  1. 倒敘
str[-1] #=> "g"
  1. 字符串比較
 if(str == sub)   #=> true
  1. 字符替換
str[3] = "1" #=> "str1ng"
  1. 字符串*
str *3 #=> "stringstringstring"
  1. 字符串+
str + "s" #=> "str1ngs"
  1. 字符串長度
str.length  str.size str.bytesize #=> 7
  1. 漢字
str = "人"   
str.length  str.size    #=> 1
str.bytesize            #=> 1
  1. 數(shù)字轉字符串
str = "a is "
a = 10.0
str + a.to_s    #=> "a is 10.0"
  1. 數(shù)組<<
str << "es"   #=> stringes
str << ?5     #=> string5
str << 5      #=> string?</pre>
  1. 字符串內(nèi)復值
sum = 5
str = "string #{sum}"   #=>  "string 5"
str = "string #{sum}  is %d %s" % [5,"sum"]    #=> "string 5  is 5 sum"</pre>

數(shù)組

  1. 聲明
arr = [1,2,3,4]
other = 1,2,3,4
a,b,c = [1,2,3]       #=> a = 1 b =2 c =3
a ,*b= [1,2,3,4]      #=> a =1 b = [2,3,4]
*a ,b= [1,2,3,4]      #=> a =[1,2,3] b = 4
  1. 支持多元數(shù)組
other = [1,2,3,4,"str"]
  1. 數(shù)組下標起始位置
arr[0] #=> 1
  1. 數(shù)組切片
sub = arr[1...3]      #=>  1,2  [1,3)
sub = arr[1,3]      #=>  1,2,3  [1, =>3長度
  1. 倒敘
arr[-1] #=> 4
  1. 數(shù)組比較
sub = [1,2,3,4]
if(arr == sub)   #=> true
  1. 數(shù)組元素替換
arr[2] = "d"  #=> [1,2,"d",4]
arr[1,3] = ["a","b"]   #=> [1, "a", "b"]
  1. 數(shù)組*
arr * 3 #=> [1,2,3,4,1,2,3,4,1,2,3,4]
  1. 數(shù)組+
 arr + [5] #=> [1,2,3,4,5]
 arr + [[5,6]] #=> [1, 2, 3, 4, [5, 6]]
  1. 數(shù)組長度
arr.length  arr.size  #=> 74
  1. 數(shù)組= #=>兩數(shù)組維持同一份拷貝
sub = arr            #=> [1,2,3,4]
arr[2] = "d" sub    #=> [1,2,d,4]
  1. Array數(shù)組深拷貝
 sub = Array.new(arr)
 if(sub == arr) #=> true
 arr[2] = "d"  sub #=> [1,2,3,4]
  1. 越界操作方式
arr[6] = 5  #=> [1, 2, 3, 4, nil, nil, 5]
  1. range對數(shù)組的初始化
 ('1'...'5').to_a #=> ["1", "2", "3", "4"]
  1. 切片賦值
arr[1...2] = ["a"]  arr #=> [1, "a", 3, 4]
arr[1,2] = ["a"]  arr #=> [1, "a", 4]
  1. 數(shù)組減法
sub = [1,2,3,4,5,6]
sub - arr    #=> [5, 6]
  1. 數(shù)組<<
 arr << 5   #=> [1, 2, 3, 4, 5]
  1. 數(shù)組&
sub = [1,3,5]
arr & sub   #=> [1, 3]
  1. 數(shù)組|
sub = [1,3,5]
arr | sub       #=> [1, 2, 3, 4, 5]
sub | arr       #=> [1, 3, 5, 2, 4]
  1. 數(shù)組遍歷
 arr.each {|x| print x}     #=>  1234

hash

  1. 初始化
nums = {:one=>1, :two=>2,:three=>3}  #=> {:one=>1, :two=>2, :three=>3}
sums = hash.new
sums[1] = 1                     #=> {1=>1}
sums = {"1"=>1, 2=>2}           #=> {"1"=>1, 2=>2}
  1. 支持多元hash
nums = {:one=>1, :two=>"2"}    #=>  {:one=>1, :two=>"2"}
  1. 獲取hash元素
nums[:one]     #=> 1
  1. 元素替換
nums[:one] = 3  #=> {:one=>3, :two=>2}
  1. hash長度
 nums.length  nums.size  #=> 3

range

  1. 初始化
 range = 1..100  #=> 1..100
  1. include? && member? && cover? 判斷
range.include?10.0      #=> true
range.include?10        #=> true
range.include?101.0     #=> false

符號

  1. respond_to?
class Greeter
    def add x, y
        x + y
    end
 end
 
gt = Greeter.new 
gt.respond_to?:add      #=> true
  1. string轉符號
puts str.to_sym  str.intern     #=> add
  1. 符號轉string
sign = :add
sign.to_sym     sign.id2name    #=> add
  1. instance_of? is_a? kind_of?
gt = Greeter.new
gt.instance_of? Greeter     #=> true
gt.is_a? Greeter            #=> true
gt.kind_of? Greeter         #=> true
  1. class
gt.class #=> Greeter
  1. ==
a = "Ruby"
b = a
c = "Ruby"
 
a == b      #=> true
a == c      #=> true
a[1] = "3"
a== b       #=> true
  1. equal?
a.equal?b       #=> true
a.equal?c       #=> false

a[1] = "3"
a.equal?b       #=> true
  1. eql?
a.equal?b       #=> true
a.equal?c       #=> true
   
a[1] = "3"
a.eql?b         #=> true
  1. <=>
1 <=> 3     #=> -1
3 <=> 3     #=> 0
4 <=> 3     #=> 1

條件式

  1. if條件
 if a == b
    "code"
 end 

 if "expr"
    "code"
 elsif "expr"
    "code"
 else
     "code"
 end

 if "expr" then
     "code"
 end

 "code" if  "expr"   #不允許有elsif else 等從句
  1. unless
unless "expr" 
    "code"
  end 

  "code" unless  "expr"   #不允許有elsif else 等從句
  1. case
 case
   when "expr" then "code"
   when "expr" then "code"
   when "expr" then "code"
   else "many" then "code"
 end
  1. until while
 until "expr" do
    "code"
 end

 "code" while "expr"
  1. for
for a in array 
    "code"
 end 
  1. times
3.times "code"  #=>0,1,2
  1. each
 data.each{|x| puts x}
  1. map
 [1,2,3,4].map {|x| puts x}
  1. upto/downto
4.upto(7) { |x| print x}   #=> 4567
  1. inject
sum = data.inject {|result , x| x +result} #=> 10
  1. yield
def five
      yield 1,2,3,4,5
  end

  five do |x,*y,z|
    print x       #=> 1
    print y       #=> [2,3,4]
    print z       #=> 5
  end

方法

  1. 函數(shù)
def func x
    return x
end
  1. 多返回值
def func x
    x
 end

 def func
    return 1 , 2
 end

 def func
    [1 , 2]
 end
  1. 單鍵方法
o = "message"
 def o.func x
    x
 end
  1. 可以定貸帶問號結尾的函數(shù)
def empty
    "code"
 end
  1. 可以用變參
def max(first, *res)
    max = first
    res.each{
      |x| max = x if x > max
    }
    max
 end
 puts max 1,2,3,4,5  #=> 5
  1. 默認參數(shù)
def sum x,y = 2,z = 3
    x + y + z
 end
  1. hash函數(shù)
def sequence args
    n = args[:n] 
    m = args[:m] 
    c = args[:c]
    a = []
    n.times {|i| a << m*i+c}
    a
 end

 puts sequence({:n=>3,:m=>5,:c=>1})
 puts sequence :n=>3,:m=>5,:c=>1  (裸hash)
  1. 代碼塊
def sequence n ,m ,c
    i = 0 
    while  i < n
      yield i * m + c
      i+= 1
    end
 end

sequence(5,2,2) {|x| puts x }       #=> 2,4,6,8,10
  1. proc對象
def makeProc &block
    block
 end

 block = makeProc {|x| puts x }  
 block.call(3)                     #=> 3
  1. proc.new
block = Proc.new {|x| puts x }
block.call(3)                     #=> 3
  1. lambda表達式
lambda = ->x{puts x }
lambda.call(3)                    #=> 3
  1. lambda表達式默認參數(shù)
lambda = ->x =3{ y = x + 1; puts y }
lambda.call           #=> 4

  1. 聲明(類名必須大寫否者報錯)
 class Point
    def initialize(x,y)
      @x,@y = x,y
    end
  
    def x; @x; end
    def y; @y; end

    def x=value; @x = value; end
    def y=value; @y = value; end

 end

 p = Point.new 3,5
  1. 枚舉坐標值
class Point
    def initialize(x,y)
      @x,@y = x,y
    end

    def each
      yield @x
      yield @y
    end
 end

 p = Point.new 3,5
 p.each {|x| print x}  #=>3,5
  1. 定義==
def == o
    if o.is_a?Point
      @x ==o.x && @y == o.y
    elsif
      false
    end
 end
  1. 定義嚴格版eql?
 def eql? o
    if o.instance_of?Point
      @x.eql?(o.x) && @y.eql?(o.y)
    elsif 
      false
    end
 end
  1. 讀寫性
attr_reader :x,:y  #=>只讀
attr_accessor :x,:y  #=>讀寫
  1. Struct方法創(chuàng)建類
 Poi = Struct.new(:x,:y)
 po = Poi.new(3,5)
 puts po.x
  1. 擁有private,public,protected的類可見性
  1. 單例方法
o = Point.new 3,5
 def o.sayBye
    puts "byebye!"
 end

 o.sayBye   #=> "byebye!"
  1. 單利方法的另外一種模式
class << o
    def sayHi
      puts "Hi"
    end
 end
  1. 單例方法查詢
puts o.singleton_methods  #=> sayBye
  1. 使用self定義的靜態(tài)方法
class SelfTest
    def self.test
      puts "hello world selfTest."
    end
 end

 SelfTest.test  #=> "hello world selfTest."</pre>
  1. 使用類名定義的靜態(tài)方法
class SelfTest
    def SelfTest.test
      puts "hello world selfTest."
    end
  end

  SelfTest.test  #=> "hello world selfTest."
  1. send調(diào)用方法
<pre>  class Base
    attr_accessor :x

    def initialize x
      @x = x
    end

    def add x ,y
      x + y
    end
  end

  o = Base.new 3
  puts o.send(:add,3,7) #=> 10
  1. module
module Model
    def sayHello
      puts "hello world!"
    end
  end

  class Base 
    include Model

    def initialize x
      @x = x
    end
  end

  o = Base.new
  o.sayHello  #=>  "hello world!"</pre>

反射,元編成

  1. class superclass 反射
 class Base
    attr_accessor :x

    def initialize x
      @x = x
    end

    def log
      puts @x
    end
  end

  o = Base.new 3
  puts o.class      #=> Base
  puts o.class.superclass #=> Object</pre>
  1. eval求值
 a = 100
 puts eval "a + 1"

正則表達式

if "Ruby" =~ /[R,r]uby/
  puts "true"
end

集合

  1. 遍歷切片遍歷
 (1...10).each_slice(3) {|x| print x} #=> [1, 2, 3][4, 5, 6][7, 8, 9]
  1. 滑動切片遍歷
 (1...10).each_cons(3) {|x| print x}  #=> [1, 2, 3][2, 3, 4][3, 4, 5][4, 5, 6][5, 6, 7][6, 7, 8][7, 8, 9]
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末显蝌,一起剝皮案震驚了整個濱河市预伺,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌曼尊,老刑警劉巖酬诀,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異骆撇,居然都是意外死亡瞒御,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門神郊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來肴裙,“玉大人趾唱,你說我怎么就攤上這事◎吲常” “怎么了甜癞?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長宛乃。 經(jīng)常有香客問我悠咱,道長,這世上最難降的妖魔是什么征炼? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任析既,我火速辦了婚禮,結果婚禮上谆奥,老公的妹妹穿的比我還像新娘眼坏。我一直安慰自己,他們只是感情好雄右,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布空骚。 她就那樣靜靜地躺著,像睡著了一般擂仍。 火紅的嫁衣襯著肌膚如雪囤屹。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天逢渔,我揣著相機與錄音肋坚,去河邊找鬼。 笑死肃廓,一個胖子當著我的面吹牛智厌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播盲赊,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼铣鹏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了哀蘑?” 一聲冷哼從身側響起诚卸,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎绘迁,沒想到半個月后合溺,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡缀台,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年棠赛,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡睛约,死狀恐怖鼎俘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情痰腮,我是刑警寧澤而芥,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站膀值,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏误辑。R本人自食惡果不足惜沧踏,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巾钉。 院中可真熱鬧翘狱,春花似錦、人聲如沸砰苍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽赚导。三九已至茬缩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吼旧,已是汗流浹背凰锡。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留圈暗,地道東北人掂为。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像员串,于是被迫代替她去往敵國和親勇哗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在C語言中,五種基本數(shù)據(jù)類型存儲空間長度的排列順序是: A)char B)char=int<=float C)ch...
    夏天再來閱讀 3,342評論 0 2
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,451評論 0 13
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile麗語閱讀 3,836評論 0 6
  • # The Ruby Style Guide > Hey jude, don't make it bad. > T...
    司徒雷斯閱讀 325評論 0 2
  • 寫在前面的話 代碼中的# > 表示的是輸出結果 輸入 使用input()函數(shù) 用法 注意input函數(shù)輸出的均是字...
    FlyingLittlePG閱讀 2,755評論 0 8