class
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.
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.
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.
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.
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.
https://www.javadrive.jp/ruby/inherit/index1.html
https://qiita.com/daddygongon/items/969ad5112878f6dab844
Recommended Posts