zoukankan      html  css  js  c++  java
  • HeadFIrst Ruby 第二章总结 methods and classes

    HeadFIrst Ruby 第二章总结 methods and classes

    前言

    这一章讲了如何创建自己的 class,并且讲了在用 class 创建 object 的两个要素: instance variables 和 instance methods.和它们需要注意的一些问题.

    创建 method 相关

    问题1:括号 be or not be?

    在 Ruby 中,如果需要创建的 method 包含参数,那么后面应该有“()” ;
    如果不需要任何参数,则不需要加“()”,在调用函数的时候也不需要加.

    问题2: local variable 和 instance variable 的区别

    local variable:在定义的 method 范围之后,就 don't exisit 了
    instance variable: 在定义的 class 的范围内都 exisit.

    新知1:在 Terminal 中运行程序的另一种方法

    特点:可以 load 这个 file 之后,然后进行交互的编程.

    步骤:

    1. 在 Terminal 中输入 “irb -I ."
    2. 接着在提示下输入 "require xxx.rb"

    新知2: atttribute accessor methods

    定义:为了实现 encapsulation,如果想要给创建的 instance 传递参数的话,就需要通过 accessor methods 进行传递,它分为两类: attribute writer 和 attribute reader

    attribute writer

    定义:用于set an instance variable
    惯例: attribute writer 的名字与 instance variable 的名字相同,结尾为 "=".
    格式: 

    def my_attribute=(new_value)
    @my_attribute = new_value
    end

    attribute writer

    定义:用于 get the value of an variable back
    格式:

    def my_attribute
    @my_attribute
    end

    attribute accessor

    可以用 

    • attr_writer :name
    • attr_reader :name
    • attr_accessor :name

    代替 def 格式的代码,它们是 equivalent 的





  • 相关阅读:
    java 编程基础 Class对象 反射:代理模式和静态代理
    sql优化(排序)
    Mysql备份恢复
    Mysql5.7.33安装
    Networker oracle备份恢复
    Centos7 安装11.2.0.4
    spring security 自定义多种方式登录授权
    CentOS 7 安装Nginx 并配置自动启动
    Nginx 配置模板
    Alibaba cloud 版本说明
  • 原文地址:https://www.cnblogs.com/FBsharl/p/10463251.html
Copyright © 2011-2022 走看看