xxxxxxxxxx
# 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
xxxxxxxxxx
class Dog # Initialize class!
def initialize(name) # Initialize function of class Dog
@name = name # Set name to param in class
end
def print_name() # Function to print out the name in params
puts @name # Puts!
end
end
my_dog = Dog.new "Bruno" # Create class and save it in variable
my_dog.print_name # Call print_name function from class
# Output:
# Bruno
xxxxxxxxxx
class Person
def initialize(name) # this is an empty class
end
end
p1 = Person.new("Ben")
class Person
def initialize(name)
@name = name #This is an instance variable
end
end
p1 = Person.new("Ben")
#To recall the name
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
#We can call the above
p2=Person.new("Brian")
puts p2.name
#Attribute writers
class Person
def initialize(name)
@name = name
end
def name
@name
end
def password=(password)
@password = password
end
end
p3=Person.new("Margret")
p3.password = "lovydovy"
p p3
xxxxxxxxxx
# 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 "\n"
end
end
# Creating objects and passing parameters
# to new method
xveh = Vehicle. new("1", "Red", "ABC")
yveh = Vehicle. new("2", "Black", "XYZ")