Outline
The data’s basic unit is the Object in Ruby. For example, the Array and Variable are the Objects. In this blog post, I will introduce the Object in Ruby.
Class and Object
The Class is a blueprint representing a property or feature ob the Object. You can create the Object form the Class.
In Objects, there is storage for the type of data, so values can be stored in objects.
Below are the Objects that are mainly used in Ruby.
Object | Description | Class Name |
---|---|---|
Number Object | Indicates the Number | Numeric, etc |
String Object | Indicates the String | String |
Regular expression Object | Indicates a matching pattern of the string | Regexp |
Time Object | Indicates the Time | Time |
File Object | Uses to read/write the file | File |
Hash Object | Indicates the Hash | Hash |
Arry Object | Indicates the Array | Array |
Method in Object
You can not only store the value in Object, but also have methods for manipulating values in the Object.
Below is the type of the Method in Class and Object.
Method type | Description | Example |
---|---|---|
Instance Method | You can call the method via Object. | “1234”.split() |
Class Method | You can call the method via Class. | File.delete |
Functional Method | Normal method | print(3) |
Conversion Method
You can convert the values by the method below in Ruby.
- Integer
puts -3.14.to_i
# -3
puts 3.14.to_i
# 3
- Float
puts -3.to_f
# -3.0
- Round
puts -3.1.round
# -3
puts 2.8.round
# 3
- Convert the string to number
# string to float
puts "123.23".to_f
# 123.23
# string to int
puts "123.23".to_i
# 123
Range Object method
You can use Range Object like below in Ruby.
for i in a..b
...
end
Also, you can use the Range class to create a range like below.
Range.new(a, b)
You can use the methods in the Range Object like below.
puts (1..5).begin
# 1
puts (1..5).first
# 1
puts (1..5).end
# 5
puts (1..5).last
# 5
You can convert the range to the array.
p (1..5).to_a
# [1, 2, 3, 4, 5]
p ("a".."d").to_a
# ["a", "b", "c", "d"]
However, you can convert only ascending order ranges.
p (-1..-5).to_a
# []
Completed
We’ve seen what Object is and how to use it in this blog post. In Ruby, the variable and array are Objects, so it’s better to always consider the Object in Ruby when you program it.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.