1
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.

第十一回講義メモ

Last updated at Posted at 2020-12-31

!Mac OS X-10.15.7 !ruby-2.6.3p62

オブジェクト指向

特に,

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

に焦点を当てる.

class

def puts_hello name
  puts "Hello #{name}."
end

def gets_name
  name = ARGV[0] || 'world'
  return name
end

name = gets_name
puts_hello name

以前使ったこのコードに置いて, main loopを消すためにクラス化する.

class Greeter
  def initialize
    @name = gets_name
    puts_hello
  end

  def puts_hello #salute
    puts "Hello #{@name}."
  end

  def gets_name
    name = ARGV[0] || 'world'
    return name.capitalize
  end
end

Greeter.new
> ruby hello_class.rb

上記で実行すると, 同じで結果を吐くことが確かめられた.

継承

以下サンプルコード.

require 'colorize'

# method
def hello(name)
  "Hello #{name}."
end

# inherited class
class Greeter < String
  def hello
    "Hello #{self}."
  end
end

# extend class
class String
  def hello
    "Hello #{self}."
  end
end

# method call
name = ARGV[0]
puts hello(name).green

# inherited class call
greeter = Greeter.new(ARGV[0])
puts greeter.hello.green

# extend class call, override
puts ARGV[0].hello.green

上記のコードにおける, class Greeter < String部分が継承にあたる.

参考サイト

https://qiita.com/daddygongon/items/969ad5112878f6dab844


  • source ~/my_ruby/grad_members_20f/members/drop-sd/lectures/no11.org
1
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
1
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?