zoukankan      html  css  js  c++  java
  • Ruby学习笔记(二)

    1.block 代码块

    do...end 或 {} 构成一个代码块,就像常见的 .each后面跟的代码块、

    my_nums = [1,2,3]
    my_double_nums = my_nums.collect {|num| num*2}
    puts "#{my_double_nums}"
    
    #=> [2,4,6]

    collect能作用在Array的每个元素上,也支持collect! 操作,即改变数组本身。map! 和 collect! 作用相同

    yield关键字 yield能够在方法内调用 block,这也是为什么有一些方法能接受一个block而另一些不行。

    Why do some methods accept a block and others don't? It's because methods that accept blocks have a way of transferring control from the calling method to the block and back again. We can build this into the methods we define by using the yield keyword

    yield也能接受参数

    def yield_name(name)
      puts "In the method! Let's yield."
      yield name
      puts "Block complete! Back in the method."
    end
    yield_name("Eric") { |name| puts "My name is #{name}." }


    2.Procs 使得我们能复用block

    Ruby中“一切皆对象”。但是,Blocks却不是对象,所以我们需要使用procs去“存储”block。

    Procs使得你的代码符合DRY-Don't Repeat Yourself特性。

    multiples_of_3 = Proc.new do |n|
      n % 3 == 0
    end
    (1..100).to_a.select(&multiples_of_3)

    &用来将multiples_of_3转换成block。当把带有&符号的参数传给方法时,会被认出是block、

    将block "save"成procs有两个主要好处:1.procs是objects,所以具有objects的能力。2.复用

    然而,你始终要记得,在Ruby中去做某些事时,总是有不止一种方法。所以,有另外的方法去调用procs:call关键字

    hi = Proc.new { puts "Hello!" }
    hi.call

    另外,symbol能当做函数名的引用去传递一个函数,symbol前加&也能转换成procs

    numbers_array = [1, 2, 3]
    strings_array = numbers_array.map(&:to_s)  
    #=> ["1","2","3"]


    3.Lambda

    与procs类似,lambdas也是对象。他们的相似之处不止于此:除了语法上的一点不同和各自某些特殊的行为,两者是几乎一样的。

    lambda {puts "Hello!"}  和 Proc.new {puts "Hello!"}  是一样的
    def lambda_demo(a_lambda)
      puts "I'm the method!"
      a_lambda.call
    end
    lambda_demo(lambda { puts "I'm the lambda!" })
    Lambda vs. Procs
     首先,lambda会检查传递给它的参数,然而procs不会。这就意味着如果你传递给lambda的参数个数不对,它就会抛出一个错误,而proc将会忽略多余的参数并讲缺少的参数赋值为nil。
      其次,当lambda返回(用return)时,它将控制权传回给方法;而当proc返回(用return)时,是不会回到方法内继续执行在它后面的代码的。
    my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages]
    symbol_filter = lambda{|item| item.is_a? Symbol}
    symbols = my_array.select(&symbol_filter)
    4.简单的总结
    Block是在do..end 或者 {} 之间的一些代码。它自己本身不是对象,但它可以传给像 .each 或 .select 这样的方法;
    Proc能够“保存”block,得以让我们能够复用它;
    Lambda跟Proc十分像,但它关心传递给他的参数个数,并且在return时能够返回到调用它的方法里(继续执行后面的代码),而不是直接也将这个方法一起return了。

    5.Class
    命名规范:首字母大写,驼峰
    Instance variables @var  类的实例的变量
    Class variables       @@var  类的变量(所有实例都拥有同一份拷贝)
    Global variables      有两种方法:1.定义在方法或类的外面(实测,即使定义在外面,若想在方法内部使用也要加$啊)。 2.若定义在方法或类内部,用$
    定义类内部静态方法   def self.func; end  或者 def ClassName.func; end
    构造函数 del initialize ... end

    Inheritance  继承 语法:  class DerivedClass < BaseClass    #Some stuff!   end
     Override.       super
     只能有一个父类

    访问控制 Ruby中默认是Public
    class ClassName
         public
         def public_method; end
         private
         def private_method; end
    end
    attr_reader :name  #定义get方法    ;   attr_writer :name #定义set方法    ;  attr_accessor :name #前两者都包含
    class Person
      attr_reader :name #name的get方法
      attr_writer :age  #age的set方法
      attr_accessor :gender  #gender的getter和setter
      
      #age的get方法,同 attr_reader :age
      def age
        @age
      end
      
      #name的set方法,同 attr_writer :name
      def name=(value)
        @name = value
      end
    end
    经测试,在使用 person = new Person; person.name="abc"时, person.name = "abc"也可以 =号不跟在name后面

    6.Module 命名规范同class    Module跟类很像,但是不能创建实例,不能有子类。
     Module中适合定义常量。使用Module的一大目的就是分隔方法和常量。这叫 namespacing。例如: Math::PI  ; Circle::PI
     scope resolution operator  ::  作用域操作符.   访问module中的变量和方法都可以用这个操作符
    Module中定义方法,如类中的静态(我认为的静态)方法(Class Methods),使用 def module_name.func;end  或者 def self.func; end
    ruby中 .self 指代当前object
    require 'module'
    include 'module' 
    When we include a module that has already been required, we pull in all its methods and constants at the instance level. That means that any class that includes a certain module can create objects (instances) that can use those very same methods!
    include之后,可以直接使用module的方法和常量,而不用加 module_name::  
    mixin 
    When a module is used to mix additional behavior and information into a class, it's called a mixin. Mixins allow us to customize a class without having to rewrite code
    module有点类似 Interface,可以被多个类include
    extend 跟include相反,mixes a module's methods at the class level. This means that class itself can use the methods, as opposed to instances of the class


  • 相关阅读:
    并发编程学习笔记(15)----Executor框架的使用
    并发编程学习笔记(14)----ThreadPoolExecutor(线程池)的使用及原理
    并发编程学习笔记(13)----ConcurrentLinkedQueue(非阻塞队列)和BlockingQueue(阻塞队列)原理
    并发编程学习笔记(12)----Fork/Join框架
    并发编程学习笔记(11)----FutureTask的使用及实现
    并发编程学习笔记(10)----并发工具类CyclicBarrier、Semaphore和Exchanger类的使用和原理
    设计模式:代理模式
    设计模式:装饰模式
    设计模式:几大原则
    设计模式:策略模式(Strategy)
  • 原文地址:https://www.cnblogs.com/pangblog/p/3257961.html
Copyright © 2011-2022 走看看