Create a namespace (Namespaces)

xiaoxiao2021-03-06  66

In general, a class define a class that makes this class in its own independent Namespace. This way your class will not have problems because of the names in other modules, such as:

Module Foo Class Joy Def Initialize (One, TWO) PUTS "ONE: [# {one}] Two: [# {two}]" end end "

Module Bar Class Joy Def Initialize (Something) Puts "Do # {something} already!" end end end

In this case, you can't define the JOY class:

Joy.new ('A', 'B') Because there is no Joy in your current NameSpace, you can define this:

Foo :: joy.new ('a', 'b') or

Bar :: joy.new ('a crossword puzzle')

Because Joy is defined in module foo and bar.

As a writer of a module, or some similar classes, you may put them in a module definition. But as a user of the module, each time you knock so many letters may be more annoying, one way is to use alias:

Joy = foo :: Joy then, you can use this alias: joy.new ('a', 'b') Another solution is to use 'incrude':

Include foo

In this way, you can use Joy directly without writing full foo :: JOY. Include Bar lets you use Joy directly without having to write all Bar :: JOY.

However, if you write the above two incrude statements, Joy will point to the last unique possible object, such as:

Include Foo Include Bar That Joy will point to Bar :: Joy. But if you write again

INCLUDE FOO JOY still will point to Bar :: JOY.

This profile also has a strict scope of the domain. If you specify an Include module in a class definition, the brief writing of this module object is valid only in this class; if you specify an incline statement in a module, you can use include in including the entire module. abbreviation of. If you don't specify NameSpace, then the default is an anonymous namespace. Moreover, if you want the variables in a file, it is best to use (especially other files), it is best to define it in the module. For example, the file foo.rb content is as follows: var1 = 99 In another file, you want to this:

Require 'file1' Puts var1 will be wrong: NameError: undefined local variable or method var1, it is best to set a VAR1 to one to a module.

转载请注明原文地址:https://www.9cbs.com/read-89883.html

New Post(0)