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

第11回(class化)

Last updated at Posted at 2020-12-07

お題:class化

解法:最初の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

これをクラスで書くと

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
Hello world
  • Greeter.new
  • class Greeter
  • initialize method
  • @name

@nameはインスタンス変数というらしい.

classはmain loopを無くして代わりにclassにし,イニシャライズを定義したもの.

解説(指向):method的かobject思考的か

methodとclassを比べるとオブジェクト指向の書き方の流儀の違いが実感できるらしい.

method名をverbとすると,

  • methodでは,verb(subject, object)
  • object指向では, subject.verb(object)

とりあえずサンプルコードを見る.

上から,method, 継承を使ったclass, classへの上乗せ(override)

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

StringをGreeterに継承しているため,GreeterはStringのメソッドを扱える.

overrideに関しては,親クラスで定義しているメソッドと同名のメソッドを子クラスで再定義するものと思っていたためここでの使い方はいまいち理解できていない.要勉強.


  • source ~/grad_members_20f/members/yoshida/c6_class_hello.org
4
0
1

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
4
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?