11th

class

Overview

This time we will deal with classes. In basic ruby, class names must start with an uppercase letter. The class definition is the assignment of the class to the constant specified by the identifier. When a class is already defined, writing a class definition with the same class name will add the class definition. However, note that if you specify a superclass different from the original class, a TypeError will occur.

program

Below is a sample program.

hello_class.rb


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

When you do this

C:\Users\nobua\M1>ruby hello_class.rb
Hello World.

#-> If you do not enter anything

C:\Users\nobua\M1>ruby hello_class.rb Ruby
Hello Ruby.   

If you enter #-> Ruby

Was output.

Commentary

The Greeter class of this program consists of three methods: ・ initialize ・ puts \ _hello ・ get \ _name. First, assign the word received at the terminal with gets \ _name or the world prepared in advance to the local variable name, and convert the initial letter to uppercase. Next, in the method initialize, assign the name defined in gets \ _name to the instance variable @name and call puts \ _hello. In puts \ _hello, @name defined by initialize is received and output in the form of "Hello # {@name}". This is the flow of this program.

Inheritance of class

Overview

As mentioned in the class section, when a class has already been created, you can extend it to create a new one. This is called class inheritance.

program

Check the method of inheriting the class with the following program.


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

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

greeter = Greeter.new(ARGV[0])
puts greeter.hello

In the program, the Greeter class inherits the String class, the String class is called the parent class of the Greeter class, and the Greeter class is called the child class of the String class.

References

https://www.javadrive.jp/ruby/inherit/index1.html

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


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)