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'