简体   繁体   English

在Ruby中调用没有模块名的模块类方法

[英]Calling module class methods without module name in Ruby

Is it possible to substitute 是否有可能替代

@m1 = MyModule.method1
@m2 = MyModule.method2
@m3 = MyModule.method3
@m4 = MyModule.method4

with something like this 有这样的东西

with MyModule do

  @m1 = method1
  @m2 = method2
  @m3 = method3
  @m4 = method4

end

in Ruby? 在Ruby?

You could do something like this: 你可以这样做:

def with(context, &block)
  yield context
end

with MyModule do |m|
  @m1 = m.method1
  @m2 = m.method2
  ...
end

I'm not totally sure what benefit this gives you - could you be more specific about how you plan to use this? 我不完全确定这会给你带来什么好处 - 你能否更具体地说明你打算如何使用它?

No, this is not possible. 不,这是不可能的。 Method calls without an explicit receiver have an implicit receiver of self , so in order to make method1 a call to MyModule.method1 , self needs to be changed to MyModule . 没有显式接收器的方法调用具有self的隐式接收器,因此为了使method1调用MyModule.method1 ,需要将self更改为MyModule That's easy enough, after all, that's what instance_eval and instance_exec are for. 毕竟,这很容易,就是instance_evalinstance_exec的用途。

However, instance variables also belong to self , that's why they are called instance variables, after all. 但是,实例变量也属于self ,这就是它们被称为实例变量的原因。 So, if you change self to MyModule , then @m1 , @m2 etc. will also belong to MyModule and no longer to whatever object they belong to in your code example. 因此,如果您将self更改为MyModule ,那么@m1@m2等也将属于MyModule而不再属于您的代码示例中它们所属的任何对象。

In other words, you need self to change but you also need self not to change. 换句话说,你需要self改变,但你也需要self改变。 That's a contradiction, ergo, what you want isn't possible. 这是一个矛盾,因此,你想要的是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM