Ruby fundamental by example – everything is an object
Apr 21, 2013 00:00 · 476 words · 3 minute read
Last week, I have attended a ruby cucumber training course which was running by Chris Parson and I have found it really useful.
Some basic definition
- Class: A template that describes an object. It is a type of object and it defines methods.
- Variable: a container for a value and it hold a reference to an object.
- Method: block of code that expose a behavior and it manipulates the objects.
- Expression: something to evaluate something else with at least one operand. It can combine objects.
In Ruby everything is an object or in other words everything has state and behavior.
Examples
Convert to string
puts 1.to_s #output: "1"
Puts 1.0.to_s #output: "1.0"
As you can see the number “1″ is an object which contain the “to_s” method.The method will convert the number one into the string format.
Convert to integer
puts "123".to_i #output: 123
Check type
You can check the type of the variable by passing it to the “is_a?()” Method
puts 1.nil? #output: false
puts 1.is_a?(Fixnum) #output: true
puts nil.is_a?(TrueClass) #output: true
You can not check the type of undefined variable
puts a.is_a?(Fixnum) #output: undefine local variable or method 'a'
Get class type
As mentioned before everything in Ruby is an object and has its own class . You can get the class type of each variable by the “Class” method.
puts "1".class #output: string
puts 1.class #output: Fixnum
puts 1.0.class #output: Float
puts nil.class #output: NilClass
puts true.class #output: TrueClass
Defining a variable
Defining and initializing the variables can be done simply as below.
puts a=2 #output: 2
Asserting the value of a variable can be done by using double equal signs
puts a==2 #output: true
puts a==3 #output: false
Although everything is an object but they are value type. That’s why we can assert two values regardless of their reference.
puts 1==1 #output: true
The type of variable is define according to it’s value. As “a” value was an integer therefore it should have the “Fixnum” type.
puts a.is_a?(Object) #output: true
puts a.is_a?(Fixnum) #output: true
puts a.is_a?(String) #output: false
You can assign new value to a variable and change its value.
puts a=a+1 #output: 3
puts a+=2 #output: 5
even the type of variable can be change by assigning a new value to it
puts a/2.0 #output: 2.5
puts a/2 #output: 2
The defined variable has access to all the method of its type
puts a.even? #output: false
This story is same to other value types such as string
puts text="hello" #output: hello
puts text=text+" hello" #output: hello hello
puts text+=" there" #output: hello hello there
Bear in mind that every operand is a method in Ruby. In below as string class do not have division method, we will encounter with a compilation error.
puts text/2 #output: error
Download
Feel free to download the full source code of this example from my GitHub