Object in Ruby

2020-12-16 hit count image

Let's see what the Object is and how to use it in Ruby

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.

ObjectDescriptionClass Name
Number ObjectIndicates the NumberNumeric, etc
String ObjectIndicates the StringString
Regular expression ObjectIndicates a matching pattern of the stringRegexp
Time ObjectIndicates the TimeTime
File ObjectUses to read/write the fileFile
Hash ObjectIndicates the HashHash
Arry ObjectIndicates the ArrayArray

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 typeDescriptionExample
Instance MethodYou can call the method via Object.“1234”.split()
Class MethodYou can call the method via Class.File.delete
Functional MethodNormal methodprint(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

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts