As a basic idea of object orientation,
--Capsulation --Inheritance --Polymorphism
there is.
This idea is incorporated not only in Ruby but also in Python and various languages.
Class
If you enter a name in the argument of the command created earlier, a greeting will be returned.
hello_method.rb
def hello name
  puts "Hello #{name}."
end
name = ARGV[0]
hello(name)
We will improve this and further classify it.
In hello \ _method.rb, I tried to return the command argument, but with this, if nothing is passed,
> ruby hello_method.rb
-> Hello .
Only a greeting is returned.
It's lonely as it is, so when you prepare the gets \ _name method and do not pass anything to the command argument
Hello world.
I will return.
greeter.rb
def hello name
  puts "Hello #{name}."
end
def gets_name
  name = ARGV[0] || 'world'
  return name
end
name = gets_name
hello name
Class this code.
class_greeter.rb
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
When you do this
> ruby class_greeter.rb
-> Hello World.
> ruby class_greeter.rb W
-> Hello W.
You can have something that returns the same output as before classifying.
here,
--class Greeter: Greeter class definition --def initialize: Function to initialize. Does it work like a constructor such as C ++? -@name: Member variable --Greeter.new: Create an instance of the Greeter class
Is the basis for classification in Ruby.
Chart type ruby-VI (hello class)
Recommended Posts