[RUBY] Special Lecture on Multi-Scale Simulation: 11th (class)

Introduction

This time, create a class that behaves the same as hello.rb below.

hello.rb


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

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

name = gets_name
puts_hello name

Make a class

class_Greeter.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

If you add @ to the beginning of a variable like @name, it will be treated as an instance variable. The initialize method is a constructor.

Class inheritance

Create Greeter \ _inherited class by inheriting String class.

class_Greeter.rb


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

greeter_inherited = Greeter_inherited.new(ARGV[0])
puts greeter_inherited.hello.green

Add method

Add hello method to String class.

class_Greeter.rb


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

puts ARGV[0].hello.red

References

Chart type ruby-VI (hello class)


Recommended Posts

Special Lecture on Multi-Scale Simulation: 11th (class)
Special Lecture on Multiscale Simulation: 8th (assert)
Special Lecture on Multiscale Simulation: 10th (Recursive)
Special Lecture on Multi-Scale Simulation: I tried to summarize the 5th
Special Lecture on Multi-Scale Simulation: I tried to summarize the 8th
Special Lecture on Multi-Scale Simulation: I tried to summarize the 7th
11th class: Class
Multiscale simulation 11
9th class: assert_equal
10th class: Recursion
8th class: rake
5th class: Output
7th class: if, else
11th :: ruby_VI (hello class)
6th class: Variables, method