(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
(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"}
(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.
Introduction to Ruby for those who want to become a professional
Recommended Posts