11th :: ruby_VI (hello class)

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

Theme: Classification

Learn how to classify in Ruby.

Solution: First class

Below is a slightly extended version of hello.rb that I did earlier.

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 is defined for the above code and classified.

Classified code

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

If you write the above code and enter the following command, it will come out properly

> ruby hello_class.rb

-Greeter.new Now you can declare Class

-@name This will be a member variable of Class

-Something like an initialize constructor

Inheritance, override

require 'colorize'

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

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

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

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

#Inheritance call
greeter = Greeter.new(ARGV[0])
puts greeter.hello.green

#Override call
puts ARGV[0].hello.green

It's very easy to write.


Recommended Posts

11th :: ruby_VI (hello class)
10th class: Recursion
8th class: rake
5th class: Output
7th class: if, else
6th class: Variables, method
5th
ruby exercise memo VI (hello class)
6th
6th
9th
7th
11th
9th
7th
11th
10th
10th
Special Lecture on Multi-Scale Simulation: 11th (class)