The difference between programming with Ruby classes and programming without it

Class-free programming

(Example)

#Create user data
users = []
users << { first_name: 'Hanako', last_name: 'Yamada', age: 8 }
users << { first_name: 'Taro', last_name: 'Yamamoto', age: 10 }

#Method to create name
def full_name(user)
  "#{user[:first_name]} #{user[:last_name]}"
end

#View user data
users.each do |user|
  puts "Full name: #{full_name(user)},age: #{user[:age]}"
end

problem

  1. With hashes, if you mistype a key, no error is displayed and nil is returned. Therefore, you may not notice the problem.
  2. Hashes tend to be "fragile and fragile programs" because new keys can be added and their contents changed.

(Example 1)

users[0][:first_name] #=> "Hanako"
users[0][:first_mame] #=> nil

(Example 2)

#Add new key without permission
users[0][:food] = 'rice'
#Arbitrarily first_Change name
users[0][:first_name] = 'dozaemon'
puts users[0]
#=> {:first_name=>"dozaemon", :last_name=>"Yamada", :age=>8, :food=>"rice"}

Programming with classes

(Example)

#Define User class
class User
  attr_reader :first_name, :last_name, :age

  def initialize(first_name, last_name, age)
    @first_name = first_name
    @last_name = last_name
    @age = age
  end
end

#Create user data
users = []
users << User.new('Hanako', 'Yamada', 8)
users << User.new('Taro', 'Yamamoto', 10)

# users[0].first_name

#Method to create name
def full_name(user)
  "#{user.first_name} #{user.last_name}"
end

#View user data
users.each do |user|
  puts "Full name: #{full_name(user)},age: #{user.age}"
end

#=>Full name: Hanako Yamada,age: 8
#Full name: Taro Yamamoto,age: 10

If you introduce the User class, an error will occur if you make a typo.

(Example)

puts users[0].first_name #=> 'Hanako'
puts users[0].first_mame #=> undefined method `first_mame' for #<User:0x00007f888d08c150> (NoMethodError)

You can also prevent adding new attributes or changing their contents.

(Example)

#I can't add attributes without permission
users[0].food = 'rice' #=> undefined method `food=' for #<User:0x00007fefae1300d8> (NoMethodError)

#Arbitrarily first_Cannot change name
users[0].first_name = 'tanjiro' #=> undefined method `first_name=' for #<User:0x00007faa210c0418> (NoMethodError)

You can also add methods inside the class.

(Example) Define the full_name method inside the User class

#Define User class
class User
  attr_reader :first_name, :last_name, :age

  def initialize(first_name, last_name, age)
    @first_name = first_name
    @last_name = last_name
    @age = age
  end

  #Method to create name
  def full_name
    "#{first_name} #{last_name}"
  end
end

#Create user data
users = []
users << User.new('Hanako', 'Yamada', 8)
users << User.new('Taro', 'Yamamoto', 10)

#View user data
users.each do |user|
  puts "Full name: #{user.full_name},age: #{user.age}"
end

#=>Full name: Hanako Yamada,age: 8
#Full name: Taro Yamamoto,age: 10

In this way, a class can hold its own data internally and have its own methods that take advantage of the data it holds. Because the data and the methods related to that data are always a set, it is easier to organize the data and methods than if you did not use a class.

Referenced literature

Introduction to Ruby for those who want to become a professional

Recommended Posts

The difference between programming with Ruby classes and programming without it
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Understand the difference between abstract classes and interfaces!
[Ruby] I thought about the difference between each_with_index and each.with_index
[Ruby] Difference between get and post
[Ruby] Difference between is_a? And instance_of?
Programming with ruby (on the way)
About the difference between "(double quotation)" and "single quotation" in Ruby
Understand the difference between each_with_index and each.with_index
[Ruby] About the difference between 2 dots and 3 dots of range object.
[Java] Check the difference between orElse and orElseGet with IntStream
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
Easy to understand the difference between Ruby instance method and class method.
Difference between Ruby instance variable and local variable
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
[Ruby] Difference between print, puts and p
[Java] Understand the difference between List and Set
[iOS] Understand the difference between frame and bounds
[Rails / ActiveRecord] About the difference between create and create!
[Ruby] Difference between puts and return, output and return value
[Ruby] Classes and instances
Ruby classes and instances
Difference between vh and%
Difference between i ++ and ++ i
Feel the basic type and reference type easily with ruby
What is the difference between a class and a struct? ?? ??
[Ruby] Difference between receiver and object. Differences between Ruby objects and JS objects
Calculate the difference between numbers in a Ruby array
[Rails] What is the difference between redirect and render?
Arbitrate the fight between PowerMock and jacoco with Gradle
[JAVA] What is the difference between interface and abstract? ?? ??
Feel the basic type and reference type easily with ruby 2
[Rails] I investigated the difference between redirect_to and render.
What is the difference between Java EE and Jakarta EE?
[Swift] UITextField taught me the difference between nil and ""
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
Difference between product and variant
Difference between redirect_to and render
Rails: Difference between resources and resources
Difference between Java and JavaScript (how to find the average)
Difference between puts and print
Difference between redirect_to and render
Difference between CUI and GUI
Difference between mockito-core and mockito-all
[Ruby] Creating code using the concept of classes and instances
Difference between class and instance
Regarding the difference between Java array and ArrayList, I compared and corresponded methods with similar functions.
Difference between bundle and bundle install
What is the difference between an action and an instance method?
Difference between ArrayList and LinkedList
Difference between render and redirect_to
Difference between List and ArrayList
[Ruby] Difference between match / scan
Difference between .bashrc and .bash_profile
[Ruby] Singular methods and singular classes
Difference between StringBuilder and StringBuffer
About Ruby classes and instances
Ruby methods and classes (basic)
Difference between render and redirect_to
Creating Ruby classes and instances
Let's override the difference between == (identity) and equals method (equivalence)