Ruby是一种理想的面向对象编程语言。面向对象编程语言的特点包括数据封装、多态性、继承、数据抽象、运算符重载等。在面向对象编程类和对象中起着重要作用。 A. 班 是创建对象的蓝图。这个 对象 也被称为 类的实例 例如,动物是一个类,哺乳动物、鸟类、鱼类、爬行动物和两栖动物是该类的实例。类似地,销售部门是类,类的对象是销售数据、销售经理和秘书。 在Ruby中定义类: 在Ruby中,可以轻松创建类和对象。只需写class关键字,后跟类名。类名的第一个字母应该是大写字母。 语法:
class Class_nameend
一个类以 结束关键字 所有的数据成员都位于类定义和end关键字之间。 例子:
# class name is Animalclass Animal# class variables@@type_of_animal = 4@@no_of_animal = 3end
使用Ruby中的“new”方法创建对象: 类和对象是Ruby最重要的部分。就像类对象也很容易创建一样,我们可以从一个类创建多个对象。在Ruby中,对象由 新方法 . 语法:
object_name = Class_name.new
例子:
# class name is boxclass Box# class variable@@No_of_color = 3end# Two Objects of Box classsbox = Box.newnbox = Box.new
这里Box是类的名称,No_of_color是类的变量。 sbox 和 nbox 是box类的两个对象。使用(=)后跟类名、点运算符和新方法。 在Ruby中定义方法: 在Ruby中,成员函数被称为方法。每个方法都由 def关键字 后跟方法名。方法的名称总是小写的,并且方法以 结束关键字 .在Ruby中, 每个类和方法都以end关键字结尾 . 语法:
def method_name# statements or code to be executedend
例子:
红宝石
# Ruby program to illustrate # the defining of methods #!/usr/bin/ruby # defining class Vehicle class GFG # defining method def geeks # printing result puts "Hello Geeks!" # end of method end # end of class GFG end # creating object obj = GFG . new # calling method using object obj.geeks |
输出:
Hello Geeks!
将参数传递给新方法: 用户可以将任意数量的参数传递给“new method”,用于初始化类变量。在向“新方法”传递参数时,必须声明 初始化 方法创建类时。initialize方法是一个特定的方法,在使用参数调用新方法时执行。 例子:
红宝石
# Ruby program to illustrate the passing # parameters to new method #!/usr/bin/ruby # defining class Vehicle class Vehicle # initialize method def initialize(id, color, name) # variables @veh_id = id @veh_color = color @veh_name = name # displaying values puts "ID is: #@veh_id" puts "Color is: #@veh_color" puts "Name is: #@veh_name" puts "" end end # Creating objects and passing parameters # to new method xveh = Vehicle. new ( "1" , "Red" , "ABC" ) yveh = Vehicle. new ( "2" , "Black" , "XYZ" ) |
输出:
ID is: 1Color is: RedName is: ABCID is: 2Color is: BlackName is: XYZ
说明: 这里是课程名称。 def 是一个用于定义 “初始化” 方法。每当创建新对象时都会调用它。每当新类方法调用它时,总是调用 初始化 实例方法。 初始化 方法就像一个构造函数,无论何时创建新对象 初始化方法 打电话。 身份证,颜色,名字, 是initialize方法和 @veh_id@veh_color,@veh_name 是initialize方法中的局部变量在这些局部变量的帮助下,我们沿着新方法传递值。“new”方法中的参数总是用双引号括起来。