#对象-34的绝对值
-34.abs
#对一个浮点数进行四舍五入处理
10.8.round
#返回一个字符串对象的大写且逆转的副本
"This is Ruby".upcase.reverse
#返回数学sin方法的参数个数
Math.method(:sin).arity
end
def area (hgt,wdth)
return hgt*wdth
end
end class Rectangle
def area hgt, wdth
hgt*wdth
end
end
def area (hgt, wdth)
@height=hgt
@width = wdth
@height*@width
end
end
def initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def area ()
@height*@width
end
end
-34.abs
#对一个浮点数进行四舍五入处理
10.8.round
#返回一个字符串对象的大写且逆转的副本
"This is Ruby".upcase.reverse
#返回数学sin方法的参数个数
Math.method(:sin).arity
图5.Ruby是全对象化的:在Ruby中,整数,浮点数,字符串,甚至类和方法都是对象。这里的代码展示了针对这些类型对象的方法调用。
在Ruby中,所有功能都是通过调用对象上的方法(或操作)实现的。事实上,Ruby中的方法调用就象其它程序语言中的函数或过程调用一样。
class Rectangleend
为了把方法添加到类,可以使用def关键字。方法的定义也应该以end关键字结束。跟随def关键字和方法名后面就是方法参数。把一个area方法添加到上面的Rectangle类的代码看上去如下所示:
class Rectangledef area (hgt,wdth)
return hgt*wdth
end
end class Rectangle
def area hgt, wdth
hgt*wdth
end
end
尽管上面代码是有效的,但是小括号还是被推荐使用于方法参数表达的,这主要是为了实现较好的可读性。
class Rectangledef area (hgt, wdth)
@height=hgt
@width = wdth
@height*@width
end
end
更确切地说,当创建一个Rectangle实例时,应该指定高度和宽度,而实例变量在此时才确定。另外,Ruby提供了一种特殊的方法initialize,它允许你建立或准备类的新实例:
class Rectangledef initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def area ()
@height*@width
end
end