[RUBY] 11th

!Ubuntu-20.04.1!ruby-2.7.1p83

This is a summary site for lectures. If you see it, please push LGTM.

What i did

--classification

Classified

theme

Let's classize the previously created hello.rb

How to write class

class is

class hogehoge
  def fugafuga
Processing content
  end
end

hogehoge.new

That is the basic form. Try to improve according to this

Practice

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

There is a method called "initialize" in the "Greeter" class, and Shioume calls the "gets \ _name" method that initialize accepts input and the "puts \ _ hello" method that outputs in order. It's pretty simple

> ruby hello_class.rb MO_data
> Hello MO_data

By naming it initialize, it seems that it will be called automatically when creating an object when this method is described in the class.

Development issues

If it ends only with hello.rb, it will be dull, so I challenged the problem of text development. The theme is "classify assert \ _equal"

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
When you do this
#+begin_src ruby
codes/assert_equal_class.rb:4: class/module name must be CONSTANT
class assert_equal

Hmm? Do I have to be CONSTANT? Doyukoto? ?? ??
It seems that the module name must start with an uppercase letter, so if you change the class name to 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

I wanted to go

Reference article

Chart type ruby-VI (hello class)


Recommended Posts

5th
6th
6th
9th
7th
11th
9th
7th
11th
10th
10th
11th class: Class
9th class: assert_equal
10th class: Recursion
8th class: rake
13th (thor, rubocop)
5th class: Output
TDD study # 2 (July 13th, 2020)
7th class: if, else
TDD study # 5 (July 18th, 2020)
TDD study # 4 (July 16th, 2020)
11th :: ruby_VI (hello class)
6th class: Variables, method
11th, Classification with Ruby
TDD study # 3 (July 15th, 2020)