2
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 3 years have passed since last update.

ruby 演習メモ VI (hello class)

Last updated at Posted at 2020-12-31

目的

ruby のコードを実際に書いてみよう.
今回は第 VI 弾.

お題

オブジェクト指向を学び, hello_method.rb を改良する. (hello_method.rb はここで書いた code)
キーとなる考え方は以下の通り.

  • 隠蔽 (capsulation)
  • 継承 (inheritance)
  • 多形 (polymorphism)

(https://qiita.com/daddygongon/items/969ad5112878f6dab844 にある課題)

今回書いた code (hello_class.rb)


class Greeter
  attr_accessor :name
  def initialize(name='world')
    @name = name
  end    

  def hello
    puts "Hello #{@name}."
  end
end

if $PROGRAM_NAME == __FILE__
  greeter = Greeter.new()
  greeter.hello
  greeter.name = ARGV[0]
  greeter.hello
end

解説

class の書き方自体は特に変わったものではない.
ただ, attr_accessor :name という書き方は知らなかった.

attr_accessor

attr_accessor は以下と等価な動作をするらしい. (ここ参照)

def name  # reader(getter)
  return @name
end
def name=(new_name) # writer(setter)
  @name = new_name
end

なるほど. これから使っていこうと思う.

参考資料


  • source ~/Lecture/multiscale_simulation/grad_members_20f/members/gagagagazelle/docs/c6_class_hello.org
2
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
2
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?