Ruby语言基础学习二:Ruby类、变量、常量、伪变量

# -*- 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值