【问题标题】:Usage of "self", mixin methods, and exposed methods“self”、mixin 方法和暴露方法的使用
【发布时间】:2014-10-23 21:46:27
【问题描述】:

这是我在名为 Game 的类中使用的一些代码:

def play
  puts "There are #{@players.length} players in #{@title}."

  @players.each do |n|
    puts n
   end

  @players.each do |o|
    GameTurn.take_turn(o)
    puts o
  end
end

它使用一行代码引用了一个名为 GameTurn 的模块。在 GameTurn 中,我有一个名为 self.take_turn 的方法:

require_relative "die"
require_relative "Player"

module GameTurn

  def self.take_turn(o)
    die = Die.new

    case die.roll
    when 1..2
      o.blam
      puts "#{o.name} was blammed homie."
    when 3..4
      puts "#{o.name} was skipped." 
    else
      o.w00t
    end
  end
end

我有点困惑为什么我们使用“self”以及模块中暴露方法和 mixin 方法之间的区别。我问了这个“instance methods of classes vs module methods

take_turn 真的是暴露的方法吗?即使我们向take_turn 方法提供了一个来自播放器类的对象,这个方法仍然被认为是我们直接使用的模块方法吗?这不被认为是一种混合方法吗?我们正在向take_turn 方法提供来自另一个类的对象,所以它不会与其他类混合吗?

另外,我仍在试图弄清楚我们何时/为什么使用“自我”一词?我们需要使用术语“self”在 GameTurn 模块中定义方法 take_turn 似乎很奇怪。好像应该不用“self”来定义吧?

【问题讨论】:

标签: ruby module self


【解决方案1】:

好的,从头开始:

self 总是返回执行它的上下文的对象。所以在这里:

class A
  self     #=> A
end

在 ruby​​ 中,您可以在飞行中的对象上定义方法,例如:

o = Object.new

o.foo   #=> NameError 

def o.foo
  :foo
end

o.foo   #=> :foo

类和模块和其他所有东西一样只是对象,因此您也可以在它们上定义方法:

def A.method
  'class method'
end

A.method    #=> 'class_method'

然而,在类体内定义它更容易也更方便——因为 self 总是返回类本身:

class A
  def self.foo
    :foo
  end
end

self 返回 A,因此可以读作:

class A
  def A.foo
    :foo
  end
end

这样做的好处是,如果您决定更改类名,您只需要在顶部进行,在 class 旁边 - 其余的将由自己处​​理。

在方法内self 始终是方法的接收者。所以:

o = Object.new
def o.method
  self
end
o.method == o       #=> true

然而,它有时可能会很混乱。常见的混淆来自于代码:

class A
  def get_class
    self.class
  end
end

class B < A
end

b = B.new
b.get_class     #=> B

尽管 get_class 是在类 A 上定义的,但 self 指的是方法的接收者,而不是方法的所有者。因此它评估为:

b.class         #=> B

出于同样的原因,类方法中的 self 总是指向执行该方法的类。

【讨论】:

  • 超级清楚,我跟着你。希望这可以为我的前进清除有关自我的问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多