Classes in Ruby
Tags :
Classes and Objects
A class is the blueprint from which individual objects are created.
Everything is an object in Ruby and objects are instances of a class. Think of a class being a mold of something and a object is the thing that was created using that mold. An object is also know as an instance of a class.
How to know to what class an object belongs to? Use the class() method on the object.
123.class()
# Fixnum
1.23.class()
# Float
"123".class()
# String
[1, 2, 3].class()
# Array
Defining our own classes.
person.rb
class Person
# Important comment: The initialize method automatically runs whenever an instance of any class is created.
def initialize(name)
@name = name
end
end
# adding your own methods to the class
class Person
def initialize(name)
@name = name
@from = "Guatemala"
end
def greet
return "Hello my name is #{@name} and I am from #{@from}"
end
end
# adding getter and setter methods
class Person
def initialize(name)
@name = name
@from = "Guatemala"
end
def name
@name
end
def name=(string)
@name = string
end
def greet
return "Hello my name is #{@name} and I am from #{@from}"
end
end
Try the following:
- Asks users a question to create your own control flow website. Be creative.
- If your logic is not working, make sure to use the parseInt() function to change a string to an integer.