# -*- coding: UTF-8 -*-
=begin
Ruby变量:
一般小写字母、下划线开头:变量(Variable)。
$开头:全局变量(Global variable)。
@开头:实例变量(Instance variable)。
@@开头:类变量(Class variable)类变量被共享在整个继承链中
大写字母开头:常数(Constant)。
=end
# 类定义
class Customer
#类变量必须先初始化,下面这个就是类变量
@@no_of_customers=0 #这个变量比较特殊,C++中没有,是在同类实例中一直存在的
def initialize(id,name,addr)#这里类似于C++中的构造函数
@cust_id=id #@cust_id是实例变量,id是局部变量
@cust_name=name
@cust_addr=addr
end #这里需要加end,
def hello #这里方法也可以不加括号,只要没有参数
puts "Hello,Ruby!"
end
def display_details()
puts "Customer id #{@cust_id}" #其中单个变量也可不加大括号
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
#创建对象
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
#调用类中的方法、
cust1.hello
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
$global_variable=10
class Class1
def print_global
puts "全局变量在 Class1 中输出为 #$global_variable" #注意要加变量类型
end
end
class Class2
def print_global
puts "全局变量在 Class2 中输出为 #$global_variable"
end
end
class1obj=Class1.new
class1obj.print_global
class2obj=Class2.new
class2obj.print_global
#Ruby常量
class Example
VAR1=100
VAR2=200
def show
puts "第一个常量的值为 #{VAR1}"
puts "第二个常量的值为 #{VAR2}"
end
end
object=Example.new()
object.show
=begin
Ruby 伪变量
它们是特殊的变量,有着局部变量的外观,但行为却像常量。您不能给这些变量赋任何值。
self: 当前方法的接收器对象。
true: 代表 true 的值。
false: 代表 false 的值。
nil: 代表 undefined 的值。
__FILE__: 当前源文件的名称。
__LINE__: 当前行在源文件中的编号。
=end
Ruby语言基础学习二:Ruby类、变量、常量、伪变量
最新推荐文章于 2021-06-03 16:53:13 发布