This is a personal memo.
Step by step to understand what a code with multiple colons ::
indicates, as shown below.
Aaa :: Bbb :: Ccc :: Ddd.new (argument :)
This is the process required to call the instance method defined in the class Ddd.
python
#Class definition
class Ddd
def hello
p "hello!!!"
end
end
Ddd.new.hello
#output
"hello!!!"
c = Ddd.new
c.hello
#output
"hello!!!"
You can either execute the method directly on the instance or store the instance in a variable and execute the method.
-Class name.new. Method name
If no argument is set for the method in the class, it is not necessary to pass the argument with new.
An error will occur if you pass unnecessary arguments.
Error example
Ddd.new.hello("aaa")
ArgumentError (wrong number of arguments (given 1, expected 0))
It is used when the method defined in the class requires an argument.
python
class Ddd
def hello2(name)
p "hello #{name}"
end
end
Ddd.new.hello2("aaa")
#output
"hello aaa"
Module name :: class name.new
python
module Ccc
class Ddd
def hello3
p "Ccc::Ddd hello3"
end
end
end
Ccc::Ddd.new.hello3
#output
"Ccc::Ddd hello3
The advantage of writing a module outside the class is that the module functions as a namespace, so you can use the same method name in different namespaces.
** ▼ Example ** If module is used as a namespace, multiple processes with the same class name and the same method name can be described.
python
#####moduleCcc
module Ccc
class Ddd
def hello3
p "Ccc::Ddd hello3"
end
end
end
#####moduleZzz
module Zzz
class Ddd
def hello3
p "Zzz::Ddd hello3"
end
end
end
##call
Ccc::Ddd.new.hello3
=> "Ccc::Ddd hello3"
Zzz::Ddd.new.hello3
=> "Zzz::Ddd hello3"
If you want to call the class (Ddd) in module Ccc and the process, use Ccc :: Ddd.new. Method name
.
Similarly, if you want to call the class (Ddd) and process in module Zzz, use Zzz :: Ddd.new. Method name
.
python
module Aaa
module Bbb
module Ccc
class Ddd
def hello
p "Aaa::Bbb::Ccc::Ddd's hello method"
end
end
end
end
end
##Method call
Aaa::Bbb::Ccc::Ddd.new.hello
=> "Aaa::Bbb::Ccc.Ddd's hello method"
python
module Aaa
module Bbb
module Ccc
class Ddd
def hello(name)
p "hello #{name}Mr. Aaa::Bbb::Ccc::Ddd method"
end
end
end
end
end
##Method call
Aaa::Bbb::Ccc::Ddd.new.hello("aaa")
=> "hello aaa. Aaa::Bbb::Ccc::Ddd method"
Aaa :: Bbb :: Ccc :: Ddd.new (argument :)
python
module Aaa
module Bbb
module Ccc
class Ddd
def hello(name1:, name2:)
p "hello #{name1}With#{name2}Mr."
end
end
end
end
end
Aaa::Bbb::Ccc::Ddd.new.hello(name2: "zzz", name1: "yyy")
=> "hello yyy and zzz"
If you specify it with a key argument, you can pass the arguments in the same order.
For class
class Aaa::Bbb
def hello(name)
p "hello #{name} !!!"
end
end
Aaa::Bbb.new.hello("aaa")
=> "hello aaa !!!"
For module
module Aaa::Yyy
class Zzz
def hello(name)
p "hello #{name} !!!"
end
end
end
Xxx::Yyy::Zzz.new.hello("bbb")
=> "hello bbb !!!"
Recommended Posts