0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

#udemyメモ studentクラス

Last updated at Posted at 2019-03-05

Attributes, getters, setters - Text directions, references and code
Section 2, Lecture 50

.rb
class Student
  attr_accessor :first_name, :last_name, :email, :username, :password
# ゲッターとセッターをメタプロでやってる(動的プロキシ?ゴーストメソッド?違いがよくわかってない)
  def initialize(firstname, lastname, username, email, password)
# Studentクラスのオブジェクトを新しく作るときに初期化して、ついでにインスタンス変数をセット
    @first_name = firstname
    @last_name = lastname
    @username = username
    @email = email
    @password = password
  end
 
  def to_s
# to_sメソッドをオーバーライドしている
    "First name: #{@first_name}, Last name: #{@last_name}, Username: #{@username},
                  email address: #{@email}"
  end
 
end
 
mashrur = Student.new("Mashrur", "Hossain", "mashrur1", "mashrur@example.com",
                      "password1")
john = Student.new("John", "Doe", "john1", "john1@example.com",
                      "password2")
puts mashrur
puts john
mashrur.last_name = john.last_name
puts "Mashrur is altered"
puts mashrur
# putsメソッドはto_sが自動的に呼び出す。わざわざto_sオブジェクトに渡さなくてもいい。
$  ruby student.rb
puts mashrur => First name: Mashrur, Last name: Hossain, Username: mashrur1,
                  email address: mashrur@example.com
puts John => First name: John, Last name: Doe, Username: john1,
                  email address: john1@example.com
puts "Mashrur is altered" => Mashrur is altered
puts mashrur => First name: Mashrur, Last name: Doe, Username: mashrur1,
                  email address: mashrur@example.com
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?