Object & Class & Variable
This chapter will introduce Ruby basic knowledge about object
, class
and variable
Table of contents
Object
Every value in Ruby is an object, even the most primitive things below
- Numeric:
1
,-10
,3.14
- String:
'foo'
,"bar"
- Data collection:
['foo', 1, 'bar']
,{ name: 'Kodacamp', floor: 3}
- Symbol:
:foo
,:bar
Class
All the objects created by Class, and have method class
.
- Numeric
- String
- Array
- Hash
- Symbol
irb(main):001:0> 1.class
=> Integer
irb(main):002:0> [].class
=> Array
irb(main):003:0> {}.class
=> Hash
irb(main):004:0> :foo.class
=> Symbol
irb(main):005:0> 'bar'.class
=> String
Variable
You can assign an object into variable, variable will record the object location in memory. We can use the variable to do data control.
Ruby has 4 kinds of variable
- local variable
- global variable
- instance variable
- class variable
local variable VS global variable
Create two files sub.rb
and scope_test.rb sub.rb
$foo = 1
bar = 1
# scope_test.rb
$foo = 0
bar = 0
puts 'print data before request sub.rb'
puts $foo
puts bar
require_relative 'sub'
puts 'print data after request sub.rb'
puts $foo
puts bar
execute ruby scope_test.rb
$~ ruby scope_test.rb
print data before request sub.rb
0 -> scope_test.rb global variable $foo
0 -> scope_test.rb local variable bar
print data after request sub.rb
1 -> sub.rb assign value 1 to global variable $foo
0 -> sub.rb assign value 1 to its local variable bar, scope_test.rb local variable bar still 0.
We do not recommend using global variable to handle data. It will let you code difficult to maintain. You will not know somewhere edit the globe variable.
We will introduce instance variables and class variables in another chapter.
Multiple assignment
- Assign 1, 2, 3 to local variable a, b, c
a = 1 b = 2 c = 3
It can use multiple assignments.
a, b, c = 1, 2, 3
If you use
*
in local variable, Ruby will put extra elements to Arrayirb(main):001:0> a,b,*c = 1,2,3,4,5 => [1, 2, 3, 4, 5] irb(main):002:0> a => 1 irb(main):003:0> b => 2 irb(main):004:0> c => [3, 4, 5] irb(main):005:0> [a, b, c] => [1, 2, [3, 4, 5]]
irb(main):001:0> a, *b, c = 1,2,3,4,5 => [1, 2, 3, 4, 5] irb(main):002:0> a => 1 irb(main):003:0> b => [2, 3, 4] irb(main):004:0> c => 5 irb(main):005:0> [a, b, c] => [1, [2, 3, 4], 5]
- Exchange values We need to use a temporary variable to store the value then exchange
irb(main):001:0> a, b = 0, 1 => [0, 1] irb(main):002:0> tmp = a -> assign local variable a's value to tmp => 0 irb(main):003:0> a = b -> assign local variable b's value to a => 1 irb(main):004:0> b = tmp -> assign local variable tmp value to b => 0 irb(main):005:0> a => 1 irb(main):006:0> b => 0
If you use multiple assignments, only one line.
irb(main):001:0> a, b = 0, 1 => [0, 1] irb(main):002:0> a, b = b, a => [1, 0] irb(main):003:0> a => 1 irb(main):004:0> b => 0