Методы экземпляра в модулях

Я всегда использую псевдонимы, с тех пор для получения надлежащей производительности на MSSQL, который необходимо снабдить префиксом схему в любом случае. Таким образом, Вы будете видеть много из

Избранный Человек. Имя От
dbo. Человек Как Человек

20
задан Gabriele Cirulli 22 February 2014 в 11:41
поделиться

4 ответа

Подумайте, что такое aux . Какой объект ответит на aux ? Это метод экземпляра, что означает, что экземпляры классов, которые включают ModName, будут отвечать на него. Сам модуль ModName не является экземпляром такого класса. Это также не сработало бы, если бы вы определили ModName как класс - вы не можете вызвать метод экземпляра без экземпляра.

Модули очень похожи на классы, которые можно смешивать с другими классами для добавления поведения. Когда класс смешивается с модулем, все методы экземпляра модуля становятся методами экземпляра класса. Это способ реализации множественного наследования.

Они также служат заменой пространств имен, поскольку каждый модуль определяет пространство имен. Но это несколько не связано. (Между прочим, классы также имеют свои собственные пространства имен,

22
ответ дан 29 November 2019 в 22:46
поделиться

the module definition evaluates to 'this is...', why?

In Ruby, everything is an expression, there are no statements or declarations. Which means that everyhing evaluates to a value. (However, this doesn't necessarily mean that it evaluates to a useful value. For example, the puts method always evaluates to nil, just like a def method definition expression (except in Rubinius, where the def expression evaluates to a CompiledMethod object for the method being defined).)

So, if everything evaluates to a value, what should a module definition expression evaluate to? Well, there are a couple of candidates: it could evaluate to nil, just like a method definition expression. Or it could evaluate to the module object itself, after all, this is what we are defining, right? But actually, Matz chose a third option: module (and class) definition expressions actually evaluate to whatever the last expression inside the module definition body evaluates to. (This allows you to easily simulate the other two possibilities by just putting nil or self as the last expression inside a module definition body.)

In your case, the last expression inside the module definition body is an assignment. But, an assignment? What the heck does that return? Isn't that a statement? No, not in Ruby. Everything is an expression, and assignments are no exception: assignment expressions evaluate to whatever the right hand side evaluates to. Here, the right hand side of the assignment expression is a string literal, which evaluates to a string object.

So, the entire module definition expression evaluates to the string 'this is a const in module'.

6
ответ дан 29 November 2019 в 22:46
поделиться
class Foo
  include ModName
end
Foo.new.aux
# output: aux
0
ответ дан 29 November 2019 в 22:46
поделиться

Вы можете сделать это так:

module ModName
  def aux
    puts 'aux'
  end
  module_function :aux
end

а затем просто позвонить:

ModName.aux
20
ответ дан 29 November 2019 в 22:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: