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. 数字转字符串
str = "a is "
a = 10.0
str + a.to_s    #=> "a is 10.0"
  1. 数组<<
str << "es"   #=> stringes
str << ?5     #=> string5
str << 5      #=> string�</pre>
  1. 字符串内复值
sum = 5
str = "string #{sum}"   #=>  "string 5"
str = "string #{sum}  is %d %s" % [5,"sum"]    #=> "string 5  is 5 sum"</pre>

数组

  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. 支持多元数组
other = [1,2,3,4,"str"]
  1. 数组下标起始位置
arr[0] #=> 1
  1. 数组切片
sub = arr[1...3]      #=>  1,2  [1,3)
sub = arr[1,3]      #=>  1,2,3  [1, =>3长度
  1. 倒叙
arr[-1] #=> 4
  1. 数组比较
sub = [1,2,3,4]
if(arr == sub)   #=> true
  1. 数组元素替换
arr[2] = "d"  #=> [1,2,"d",4]
arr[1,3] = ["a","b"]   #=> [1, "a", "b"]
  1. 数组*
arr * 3 #=> [1,2,3,4,1,2,3,4,1,2,3,4]
  1. 数组+
 arr + [5] #=> [1,2,3,4,5]
 arr + [[5,6]] #=> [1, 2, 3, 4, [5, 6]]
  1. 数组长度
arr.length  arr.size  #=> 74
  1. 数组= #=>两数组维持同一份拷贝
sub = arr            #=> [1,2,3,4]
arr[2] = "d" sub    #=> [1,2,d,4]
  1. Array数组深拷贝
 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对数组的初始化
 ('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. 数组减法
sub = [1,2,3,4,5,6]
sub - arr    #=> [5, 6]
  1. 数组<<
 arr << 5   #=> [1, 2, 3, 4, 5]
  1. 数组&
sub = [1,3,5]
arr & sub   #=> [1, 3]
  1. 数组|
sub = [1,3,5]
arr | sub       #=> [1, 2, 3, 4, 5]
sub | arr       #=> [1, 3, 5, 2, 4]
  1. 数组遍历
 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. 函数
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. 可以定贷带问号结尾的函数
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. 默认参数
def sum x,y = 2,z = 3
    x + y + z
 end
  1. hash函数
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表达式默认参数
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方法创建类
 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定义的静态方法
class SelfTest
    def self.test
      puts "hello world selfTest."
    end
 end

 SelfTest.test  #=> "hello world selfTest."</pre>
  1. 使用类名定义的静态方法
class SelfTest
    def SelfTest.test
      puts "hello world selfTest."
    end
  end

  SelfTest.test  #=> "hello world selfTest."
  1. send调用方法
<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]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,281评论 0 2
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,423评论 0 13
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 3,821评论 0 6
  • # The Ruby Style Guide > Hey jude, don't make it bad. > T...
    司徒雷斯阅读 309评论 0 2
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 2,708评论 0 8