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
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.
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 hello method to String class.
class_Greeter.rb
class String
def hello
"Hello #{self}."
end
end
puts ARGV[0].hello.red
Chart type ruby-VI (hello class)
Recommended Posts