(一)Ruby中一切都是对象,包括一个常数.
比如可以用.class属性来查看一个对象的类型,你可以看下1.class,会发现常数1的类型是Fixnum,1不过是Fixnum的一个实例。还可以使用-37这个Fixnum的实例方法abs来取得绝对值:-37.abs()会返回37
又如输入一个1.1.class,会返回Float。
(二)Ruby语法
Ruby中的类以class开始 以end结束,类名首字母的约定是大写。
Ruby中的方法以def开始 以end结束,方法名首字母的约定是小写。
Ruby中的局部变量名首字母的约定是小写。
Ruby中的构造函数名称为initialize。
Ruby中的成员变量(实例变量)前导@符,在initialize里进行声明与初始化。
Ruby中的属性用attr_writer和attr_reader声明,分别对应c#的set,get,使用了attr_accessor是可读也可写
Ruby中的全局变量前导$符。
Ruby中的常数(常量)用大写字母开头,约定是全部大写。
Ruby中任何的表达式都会返回值,sample
class
Rectangle
def
initialize(wdth, hgt)
@width
=
wdth
@height
=
hgt
end
def
width
=
(wdth)
@width
=
wdth
end
end
![](/Images/OutliningIndicators/None.gif)
r
=
Rectangle.new(
2
,
3
)
puts r.width
=
5
#
output 5
puts r.width
#
error! because the width not support read
继续补充下attr_accessor的使用,sample
class
Rectangle
attr_accessor :width
attr_accessor :height
attr_accessor :width2
attr_accessor :height2
def
initialize(wdth, hgt)
@width
=
wdth
@height
=
hgt
end
def
area()
return
@width
*
@height
end
def
area2()
return
@width2
*
@height2
end
end
![](/Images/OutliningIndicators/None.gif)
r
=
Rectangle.new(
2
,
3
)
r.width
=
5
#
give samename's variable value
r.height
=
5
puts r.area()
#
outputs is 25
r.width2
=
6
#
not samename's variable create
r.height2
=
6
puts r.area2()
#
outputs is 36
上面的代码说明了,在使用attr_accessor的时候,会寻找是否有同名的成员变量,如果有则访问同名成员变量,如果没有会默认创建一个前导@的成员变量
(三)神奇的操作符重载
Ruby支持操作符重载,而且很神奇!
class
Rectangle
attr_accessor :width
attr_accessor :height
def
initialize(wdth, hgt)
@width
=
wdth
@height
=
hgt
end
def
area()
return
@width
*
@height
end
def
+
(addRectangle)
return
self.area
+
addRectangle.area
end
![](/Images/OutliningIndicators/None.gif)
end
![](/Images/OutliningIndicators/None.gif)
r1
=
Rectangle.new(
2
,
2
)
r2
=
Rectangle.new(
3
,
3
)
puts r1
+
r2
#
operator override
puts r1
+
(r2)
puts r1.
+
(r2)
#
standard function calling format
神奇吧,其实把+号理解为一个函数的名字最好不过了,就像最后一个写法,哈哈。
(四)参数的传递
参数的传递中有默认值与可变长参数两个比较有特点的地方,其他语言有的,ruby也有。
1.参数的默认值
默认值的设置很简单,与其他语言一样,sample
class
Rectangle
attr_accessor :width
attr_accessor :height
def
initialize(wdth
=
2
, hgt
=
2
)
@width
=
wdth
@height
=
hgt
end
def
area()
return
@width
*
@height
end
![](/Images/OutliningIndicators/None.gif)
end
![](/Images/OutliningIndicators/None.gif)
r1
=
Rectangle.new
puts r1.area
看到了吧,使用默认值了
2.可选参数,可变长参数 sample
class
ParamSample
def
sayHello(
*
names)
puts names.
class
puts
"
Hello #{names.join(
"
,
"
)}!
"
end
end
![](/Images/OutliningIndicators/None.gif)
ps
=
ParamSample.new
ps.sayHello
#
output Array Hello !
ps.sayHello(
"
lee
"
,
"
snake
"
)
#
output Array Hello lee,snake!
可以看出,可变长参数前缀*号,可变长参数的实质是一个Array,呵呵。