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.

第11回 :: ruby_VI(hello class)

Last updated at Posted at 2020-12-25

!Mac OS X-10.15.7 !ruby-2.7.1p83$

お題:class化

Rubyでclass化の方法を学ぶ.

解法:最初のclass

前にやったhello.rbを少し拡張したバージョンを下記に記載.

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

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

name = gets_name
puts_hello name

上記のコードに対して,Hello Classを定義してclass化を行う.

Class化したコード

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

-Greeter.newこれでClassの宣言が可能

-@nameこれはClassのメンバー変数になる

-initializeコンストラクタみたいなやつ

継承、オーバーライド

require 'colorize'

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

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

# オーバーライド
class String
  def hello
    "Hello #{self}."
  end
end

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

# 継承の呼び出し
greeter = Greeter.new(ARGV[0])
puts greeter.hello.green

# オーバーライドの呼び出し
puts ARGV[0].hello.green

めっちゃ簡単に書ける.


  • source ~/grad_members_20f/members/okamoto0910/article/c11.org
2
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
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?