ruby语言

Ruby语言学习

几个难点学习理解

  • ruby语言是比较简单的一门语言,因为它的一切设计原则是面向对象的,所以,使用起来特别方便。当然,主要是由于它具有与Python、swift等等相似的语法特点,使得他使用起来十分方便。

下面归纳几个常遇到的问题。

1.关于变量的可读可写。
attr_reader : name表示name只读
attr_write : name表示name只写
attr_accessor: name表示可读可写。
2.关于module.
  • module与Class类似,可以在其中定义方法,然后在其他类中使用。比如可以有以下方式的引用。
    module M
            def mm
                puts "helloworld!"
            end
        end

    class A
        include M

        def initalize
            puts "aa"
        end
    end

    a = A.new
    a.mm

~~~

3.关于关键字public以及关键字private
  • public表示公共借口,可以在其他类中使用这个类的借口函数。而private表示只有在自身类中可以使用,其他类不能使用。
class Application
    attr_accessor :status
    def initialize
    end

    public
    def print_status
        puts "all system go!"
    end

    private
    def password
        @password = 123456
    end
end
4.关于区部变量和全局变量。
@重新引用的实例变量。
@@class variable
$golbal variables

例如:

class Person
    @@people_count = 0

    def initialize
        @name = name
        @@people_count += 1
    end

    def self.number_of_instances
        @@people_count
    end
end

matz = Person.new("A")
dhh  = Person.new("B")

puts "Number of Person instances:#{Person.number_of_instances}"


输出结果:
Number of Person instances:2
5.关于继承的理解
class ApplicationError
    def display_error
        puts "Error!Error!"
    end
end

class SuperBadError < applicationError
end

err = SuperBadError.new
err.display_error


输出:
Error!Error!
6.关于重写override
class Creature
    def initialize(name)
        @name = name
    end

    def fight
        return "Punch to the chops!"
    end
end

class Dragon < Creature
    def fight
        return "Breathes fire!"
    end
end
  • 可以继承下面形式:
class Dragon < Creature
    def fight
        puts "Instead of breathing fire..."
        super
    end
end
  • 继承重写部分函数后,结果可能为空,或者以改变后的函数为准。
class Message
    @@messages_sent = 0

    def initialize(from,to)
        @@message_sent += 1
        @from = from
        @to   = to
    end
end

my_message = Message.new("from","to")

class Email < Message
    def initialize(subject)
        @subject = subject
    end
end


输出结果:
nil
  • 继承的复习
class Message
    @@messages_sent = 0

    def initialize(from,to)
        @@message_sent += 1
        @from = from
        @to   = to
    end
end

my_message = Message.new("from","to")

class Email < Message
    def initialize(from,to)
        super
    end
end


输出结果:
nil
7.关于类class引用另一个类class,同一个.rb文件直接引用,不同的文件引用即可。一般使用require或者require_relative来引用。
require '*.rb'

require_relative '*.rb'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值