3
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回

Posted at

!Ubuntu-20.04.1 !ruby-2.7.1p83

これは講義用のまとめサイトです。見た人は是非LGTMを押しといてください。

やったこと

  • class化

class化

お題

以前作ったhello.rbをclass化しましょう

classの書き方

classは

class hogehoge
  def fugafuga
    処理内容
  end
end

hogehoge.new

というのが基本形。これに従って改良してみる

実践

class Greeter
  def initialize
    @name = gets_name
    puts_hello
  end

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

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

Greeter.new

「Greeter」クラスの中に「initialize」というメソッドがあり、initializeが入力を受け付ける「gets_name」メソッド、出力を行う「puts_hello」メソッドを順に呼び出すという塩梅。まあ至ってシンプルですね

> ruby hello_class.rb MO_data
> Hello MO_data

initializeって名前にすることで、このメソッドをクラス内に記述した時にオブジェクト作成時に自動的に呼び出されるらしい

発展問題

hello.rbだけで終わると味気ないのでテキストの発展問題に挑戦。お題は「assert_equalをclass化せよ」

require 'colorize'

class assert_equal
  def initialize
    assert_equal(1,1)
    assert_equal(1,2)
    assert_not_equal(1,2)
    assert_not_equal(1,2)
  end

  def puts_vals(expected, result)
    p ['expected',expected]
    p ['result',result]
  end

  def assert_equal(expected,result)
    puts_vals(expected, result)
    if expected == result
      puts 'succeeded in assert_equal'.magenta
    else
      puts 'failed in assert_equal'.cyan
    end
  end

  def assert_not_equal(expected,result)
    puts_vals(expected, result)
    if expected == result
      puts 'failed in assert_not_equal'.magenta
    else
      puts 'succeeded in assert_not_equal'.cyan
    end
  end
end

assert_equal = assert_equal.new
#+end src
これを実行すると
#+begin_src ruby
codes/assert_equal_class.rb:4: class/module name must be CONSTANT
class assert_equal

ん?CONSTANTでないといけない?ドユコト???
調べるとモジュール名は大文字で始めないといけないらしいので、class名をAssert_equalに変更すると

["expected", 1]
["result", 1]
succeeded in assert_equal
["expected", 1]
["result", 2]
failed in assert_equal
["expected", 1]
["result", 2]
succeeded in assert_not_equal
["expected", 1]
["result", 2]
succeeded in assert_not_equal

いけたいけた

参考記事

チャート式ruby-VI(hello class)


  • source ~/MasahiroOba/grad_members_20f/members/MasahiroOba/chapter11.org
3
0
2

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