美文网首页
Ruby基础

Ruby基础

作者: yaya_pangdun | 来源:发表于2016-03-29 19:02 被阅读51次
    1、数组和散列表
    a = ['ant', 'bee', 'cat', 'dog']
    
    a = %w{ant bee cat dog}
    
    inst_section = {
        'cello'    => 'string',
        'clarinet'  => 'woodwind',
        'drum'      => 'percussion',
        'oboe'      => 'woodwind'
    }
    
    $greeting = "Hello world" #全局变量
    
    2.block的使用
    ['cat', 'dog', 'horse'].each {|name| print name}
    
    3.times {print 'i'} # 0,1,2
    
    3.upto(6) {|i| print i} #3,4,5,6
    
    ('a'..'e').each {|char| print char}
    ##############如何调用block#####################
    def call_block
      puts "begin the method"
      yield("hello", 1)
      yield("hello", 2)
      puts "end the method"
    end
    
    call_block {|greet, time| puts "#{greet}, #{time}"}
    #begin the method
    #hello, 1
    #hello, 2
    #end the method
    ################################################
    
    def block_test
      if block_given? #函数后面给block了
        yield "give the block"
      else
        puts "give no block"
      end
    end 
    
    ##############block其他方式########################
    def call_block(&block)
      block.call
    end
    #&代表的是块转变为Proc(block to proc conversion)
    call_block {puts "block的另一种调用"}
    
    p = Proc.new {puts "block的其他调用"}
    call_block(&p)
    
    ##################map函数用法#####################
    name_list = ["chareice", "angel"]
    name_list.map(&:upcase)  # => ["CHAREICE", "ANGEL"]
    

    3.类

    class Song
      def initialize(name, artist, duration)
        @name = name
        @artist = artist
        @duration = duration
      end
      def to_s
        "Song : #{@name}--#{@artist} (#{@duration})"
      end
    end
    
    song = Song.new("Bicy", "Fleck", 260)
    puts song.to_s
    
    继承
    class KaraokeSong < Song
      def initialize(name, artist, duration, lyrics)
        super(name, artist, duration)
        @lyrics = lyrics
      end
    
      def to_s
        super + "[#@artist]"
      end
    end
    
    get方法
      def name
        @name
      end
      def artist
        @artist
      end
      def duration
        @duration
      end
    
    get更简单的方式
      attr_reader :name, :artist, :duration
    
    set方法
      def duration=(new_duration)
        @duration = new_duration
      end
    
    set更简单的方法
      attr_writer :duration
    

    4.类方法

    class SongList
      MAX_TIME = 5 * 60
      
      def SongList.is_too_long(song)
        return song.duration > MAX_TIME
      end
    end
    

    5.单例模式

    class MyLogger
      private_class_method :new  #private的类方法
      @@logger = nil
      def Mylogger.create  #def self.create
        @@logger = new unless @@logger
        @@logger
      end
      
      class <<self #类方法的第三种方式
        def create
          @@logger = new unless @@logger
          @@logger
        end
      end
    end
    

    ⬆对比private_class_method

    class MyTest
      def print_hello
        puts "hello"
      end
    
      private :print_hello #private实例方法
    end
    

    6.类的访问控制

    在Ruby中对象的方法默认是public,Ruby中一切都是对象,对象之间赋值采用的是引用传递

    7.容器类

    数组
    a = [1, 3, 5, 7, 9]
    
    a[1, 3]  ->[3, 5, 7]
    
    a[1..3]  ->[3, 5, 7]
    
    a[1...3]  ->[3, 5]
    

    8.实现管理song的容器

    class SongList
      def initialize
        @songs = Array.new
      end
    
      def append(song)
        @songs.push song
        self
      end
    
      def delete_first
        @songs.shift
      end
    
      def delete_last
        @songs.pop
      end
      
      def [](index)
        @songs[index]
      end
    end
    
    实现查找
    def with_title
        @songs.find {|song| title == song.name}
    end
    #查找到第一个就返回
    
    inject方法
    [1, 3, 5, 7].inject(0) {|sum, element| sum+element}
    
    [1, 3, 5, 7].inject(1) {|product, element| product * element]
    

    block做闭包回调

    class Button
      def initialize(label, &action)
        @action = action
        @label = label
      end
    
      def button_pressed
        @action.call(self)
      end
    end
    
    button = Button.new("play") {puts 'play the music'}
    #将后面的block传给&action
    
    常见的迭代器
    3.times {print "X "}
    1.upto(5) {|x| print x, " "}
    (1..5) {|x| print x}
    99.downto(90) {|x| print x, " "}
    50.step(80, 5) {|x| print x, " "}
    

    document生成字符串

    string = <<END_OF_STRING
      The body of the string
      is the input lines up to
      one ending with the same text '<<'
    END_OF_STRING
    
    字符串处理
    #chomp去除行末的换行符
    file, length, name, title= string.chomp.split(/\s*\|\s*/)
    name.squeeze!(" ") #去除多余的空格,留一个(!),不带!空格全去除
    
    

    区间

    digits = 0..9
    puts digits.include?(5)
    puts digits.min
    puts digits.max
    puts digits.reject {|i| i<5}
    digits.each {|digit| print digit}
    
    (0..9).to_a
    

    正则表达式

    a = Regexp.new('^\s*[a-z]')
    
    if line =~ /perl|python/
      puts "Scripting language mentioned:#{line}"
    end
    匹配之后Ruby会设置一些变量
    $& ->模式匹配的那部分字符串
    $` -> 匹配之前的那部分字符串
    $' -> 匹配之后的那部分字符串
    

    不定参数

    def log(*infos)
      infos.each {|info| puts info}
    end
    

    符号和字符串

    "name".to_sym()       #:name
    :name.to_s()             #"name"
    

    类型判断

    :name.is_a?(Symbol) #true
    "name".is_a?(String) #true
    

    重磅方法

    带"!"方法返回的对象本身,普通方法返回的是对象的拷贝
    
    9. 对象的内存
    per1 = "Tim"
    per2 = per1 #别名
    per1[0] = 'J'    #per2 == "Jim"
    
    per1 = "Tim"
    per2 = per1.dup #复制
    per1[0] = 'J'
    per1  -> "Jim"
    per2 -> "Tim"
    
    per = "Tim"
    per.freeze
    per[0] = 'J'  #raise a TypeError
    

    10. 计算数组的维度

    module ObjectExtension
      refine Object do
        def dimension
          return 0 if self.class != Array || self.empty?
          max = 0
          self.each do |a|
            t = a.dimension
            max = [max, t].max
          end
          max + 1
        end
      end
    end
    
    using ObjectExtension
    
    puts [1,[124,4], [1,2,3]].dimension
    
    11. 技巧
    songDuration = "2:58"
    mins, secs = songDuration.split(/:/)
    mins, secs = songDuration.scan(/\d+/)
    
    12. 可选参数
    #params={}可以替换成**params
    def advance_search(key_words, params={})
      default_params = {
        page: 1,
        paging_size: 20,
        mode: 'text'
      }
      params = default_params.merge params
    
      puts params
    end
    

    相关文章

      网友评论

          本文标题:Ruby基础

          本文链接:https://www.haomeiwen.com/subject/sejokttx.html