Explain classes and objects to a complete beginner
classes is like a blue print to create object. object is like a bundle of variables + methods.
in Ruby, most things are objects
String is an object. It has states. For example, when called length method, it will return the number of characters for that string. It also has methods, for example (+) will append another string to the end of the first string.
So if you have a custom object like computer
class Computer
attr_accessor :mouse
def turn_on
end
end
It is capable to turning on. However, this is just the design of the computer object. In order to manufacture the object, you have to raise the following method calls.
Computer.new
This will create a new computer object, which you can save into a local variables
computer1 = Computer.new
Now, suppose we create a new object , mouse = Mouse.new, we could pass in mouse into computer for them to interact with each other.
class Mouse
def click
end
end
mouse1 = Mouse.new
computer1.mouse = mouse1
computer1.mouse.click
So now we are able to ask computer to use the mouse to execute the method "click". Hence, computer object is interacting with mouse.
Similarly, array could interact with string
['hello', 'world'] << 'you'
This will create
['hello', 'world', 'you']
Now, if we want to interact with string object from array, we could call the method array.map(&:length). This will return the length of each word in the array.
classes is like a blue print to create object. object is like a bundle of variables + methods.
in Ruby, most things are objects
String is an object. It has states. For example, when called length method, it will return the number of characters for that string. It also has methods, for example (+) will append another string to the end of the first string.
So if you have a custom object like computer
class Computer
attr_accessor :mouse
def turn_on
end
end
It is capable to turning on. However, this is just the design of the computer object. In order to manufacture the object, you have to raise the following method calls.
Computer.new
This will create a new computer object, which you can save into a local variables
computer1 = Computer.new
Now, suppose we create a new object , mouse = Mouse.new, we could pass in mouse into computer for them to interact with each other.
class Mouse
def click
end
end
mouse1 = Mouse.new
computer1.mouse = mouse1
computer1.mouse.click
So now we are able to ask computer to use the mouse to execute the method "click". Hence, computer object is interacting with mouse.
Similarly, array could interact with string
['hello', 'world'] << 'you'
This will create
['hello', 'world', 'you']
Now, if we want to interact with string object from array, we could call the method array.map(&:length). This will return the length of each word in the array.
Comments
Post a Comment