Introduction to Objects and classes¶
EVERYTHING IN RUBY IS AN OBJECT, read that again and let it sink in
One more time EVERYTHING IN RUBY IS AN OBJECT.
This is the most amazing thing about ruby as a language.Worry not the amusement is coming wait for it.
What is an object?¶
By definition, an object is an instance of a class(don't worry much about that). I hate that definition,and you will soon join me, hopefully, I want you to think of an object as the universe of ruby data manipulation(this is a de facto definition of programming). For data to be transformed object receives a message which asks it do to something. This the design principle object-oriented programming(OOP which ruby is a member.OOP principle real world a composed of a group of things(objects) that has tasked to and wait for someone to ask to do it.
sending messages to Object¶
Remember the method call structure where we had the receiver,.(dot) and the message, a receiver is always an object.
"yourname".upcase
, "yourname" is an object and it is capable of upcasing itself and it is simply waiting to ask it to that therefore when asking you be it, upcase itself is does so graciously(I think deep down it says with pleasure).
1 2 3 | $irb > "yourname".upcase => "YOURNAME" |
In real life conversion, we will be like
Me: "your name" will you kindly upcase
yourself?
"your name": "not a problem"
"your name": "YOURNAME"
Let's go through another example "yourname" == "yourname"
.
1 2 3 | $irb >"yourname" == "yourname" => true |
What do think the conversation will be?.
Me: "yourname" do consider yourself to be equal to "yourname"
"yourname": true(yes)
Deep down in "yourname"'s mind this guy is nuts how can he asking if am equal to myself
Exercise¶
This help of ruby doc ask:
-
[10, 5, 10, 3, 100] to arrange elements inside it from smallest to largest
-
ask 100 to increase itself by 5
-
{"name" => "Jane Doe", "gender" => "female", "age" => 18} to give you all the keys it has and all the values it has
We said objects has tasked they can to and simply waiting to be asked to do it, what if the object is not capable of performing the tasked it is told to perform. For instance, if I ask to you fly, you will look at red-eyed and start questioning my sanity. The same applies to object if you tell an object do to what is not capable of it will question your sanity, it won't but it will throw an error
Let's try asking our ever obedient object "yourname" to sit
"yourname".sit
1 2 3 | $irb >"yourname".sit >NoMethodError (undefined method `sit' for "yourname":String) |
NoMethodError
"yourname" is simply complainining that is doesn't know how to sit
.
Not run into such problem ruby gives you the ability to ask the object wether it capable of doing
what you are about ask it to do.It is like me asking you wether you fly before asking you to do
so.This method is respond_to?
.It is used to ask object to look at itself and see wether it has
the ability to something
Let's ask our object if truly know how to upcase
1 2 3 4 | $irb > "yourname".respond_to?("upcase") => true |
How about if I know how to sit
1 2 3 | $irb >"yourname".respond_to?("sit") > false |
You can always list all methods an object can respond to using methods
method.For instance we can
ask "yourname" all methods it understand like so:
1 2 3 | $irb > "yourname".methods => [:to_r, :encode, :encode!, :include?, :%, :*, :+, :count, :partition, :sum, :next, :casecmp, :casecmp?, :insert, :bytesize, :match, :match?, :succ!, :<=>, :next!, :upto, :index, :replace, :==, :===, :chr, :=~, :rindex, :[], :[]=, :byteslice, :getbyte, :setbyte, :clear, :scrub, :empty?, :eql?, :[email protected], :downcase, :scrub!, :dump, :undump, :upcase, :[email protected], :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :freeze, :inspect, :bytes, :chars, :codepoints, :lines, :reverse, :reverse!, :concat, :split, :crypt, :ord, :length, :size, :grapheme_clusters, :succ, :start_with?, :center, :prepend, :strip, :rjust, :rstrip, :ljust, :chomp, :delete_suffix, :sub, :to_str, :to_sym, :intern, :sub!, :lstrip, :<<, :to_s, :to_i, :to_f, :gsub!, :chop!, :chomp!, :delete_prefix, :gsub, :chop, :end_with?, :scan, :tr, :strip!, :lstrip!, :rstrip!, :delete_prefix!, :delete_suffix!, :delete!, :tr_s, :delete, :squeeze, :tr!, :tr_s!, :each_grapheme_cluster, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :b, :slice, :slice!, :hash, :encoding, :force_encoding, :unicode_normalize, :valid_encoding?, :ascii_only?, :to_c, :rpartition, :unicode_normalize!, :unicode_normalized?, :unpack, :unpack1, :between?, :<=, :>=, :clamp, :<, :>, :buggy_sum, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_set, :protected_methods, :instance_variables, :instance_variable_get, :private_methods, :public_methods, :public_send, :method, :public_method, :singleton_method, :define_singleton_method, :extend, :to_enum, :enum_for, :!~, :respond_to?, :object_id, :send, :display, :nil?, :class, :singleton_class, :clone, :dup, :itself, :yield_self, :then, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :equal?, :!, :instance_exec, :!=, :instance_eval, :__id__, :__send__] |
So many right.yep it understand all those.
Introduction to classes¶
You remember me saying do not worry about the definition of an object, I said an object is an instance of class and what exactly do that mean. To understand that let's see what class is. Class is a form of grouping, we group which to things which are similar together and from there we create an object which knows how to do those things. What to think am talk about when I say knows how to
-
walk
-
eat
-
sleep
-
cook
-
laugh
Person right?, since this methods are related a can put them together in class named Person, and expected every person to how to do all the above(with exceptional cases but you get the point. Therefore when I tell a person named janedoe to run she will know how to run. In this case person(the group) has the blueprint of what all every person can do.Therefore janedoe being from that group know how to do everything related to person.
We have two types of class:
-
inbuilt
-
user defined
Inbuilt class¶
These are class which come shipped with ruby language: The include but not limited to:
-
Integer
-
Array
-
String
-
Float
-
Hash
-
File
-
BasicObject
User defined¶
These are written by you to suit you needs where necessary
Syntax of class is like:
Note that class name start with a capital letter and conventionally at start of every word this denotes constants in ruby while this doesn't mean they cannot be changed but its always a good practice never to change values or definition of constant, we trust in you to practise due diligence.
1 2 3 4 5 6 7 8 9 10 11 12 | $irb > class Person > def walk > "I am walking" > end > def run > "I can run" > end > def laugh(how) > "I am laughing #{how}" > end > end |
creating objects¶
Objects are created from classes.The process of creating an object is known as instantiation
From inbuilt class¶
Ruby has several inbuilt class String
, Integer
, Hash
, Array
and so on
When write literal 2
you are creating an object 2
which is an instant of class Integer
therefore
it know all the methods that are in the class Integer
for instance methods to_s
is used to tell
instance of Integer
to convert themselves to string
.Let us see if 2 knows how to respond to that
1 2 3 | $irb > 2.to_s > "2" |
you can always assing use a placeholder(variable) for literally for later manipulation like so
1 2 3 4 | $irb > x = 2 > x.to_s > "2" |
Since everything in ruby is object class are object too therefore we can create new instance of class using new
methods. Any other objects not all class understand new
.For examples
1 2 3 | $irb >Integer.new >NoMethodError (undefined method `new' for Integer:Class) |
Integer class (object) this case - remember our phrase receiver is always an object.Doe not how
to respond to new
method
1 2 3 | $irb > Array.new => [] |
This is creates an empty array.Though this not a common practise.I bring out our point that everything is an object.If I want an array I would use literal like so:
1 2 3 | $irb > [] => [] |
From user defined class¶
We instantiate an object from our defined class by
passing new
method to the class. In this example we have class Person
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $irb > class Person > def walk > "I am walking" > end > def run > "I can run" > end > def laugh(how) > "I am laughing #{how}" > end > end 12. > person1 = Person.new > person1.walk => I am walking > person1.laugh("loudy") =>I am laughing loudly |
We call Person.new assigning it variable person1.
person1 which is our object(instant of class Person), know how perform all methods in Person class.Therefore when we as ask to walk
it respond greatly "I am walking". When we to laugh, loudly in doess just that.But when asked to sleep
it can't because it doesn't know how.
In nutshell class is you teach object you intended to create how to do things.
Let's create BankTransaction class which contain methods(instructions) well for tranction to occur.
On your terminal create a file bank_transaction.rb like so:
1 | $touch bank_transaction.rb
|
In the bank_transaction.rb file had this code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class BankTransaction def just_arrived puts "pick your ticket from the machine" end def have_picked_up_ticket puts "sit and wait for your turn" end def have_valid_id?(response) response = response.downcase if response == "yes" "transaction occurs will occur" else "no transaction" end end end |
Exercise¶
-
create an instance of class BankTransaction assigning it variable equity
-
ask equity wether it understand method just_arrived
-
ask equity all the methods it understand
-
What will be the output if call equity with have_valid_id? with "No" as the arguement.
-
Create a class Animal with methods,
reproduce
,die
andgrow
.The returns values of each method should be anything you choose.v -
Create an instance of the class(Animal) you have created and asking to reproduce, grow, die and eat.
-
What are you outputs?,try explaining them