SORU
30 Mart 2009, PAZARTESİ


Nasıl bir modülü başlatılamıyor'ruby'de örnek değişkenleri s miyim?

Örnek değişkenleri kullanmak istiyorum bazı modüller var. Şu anda bu şekilde başlatıyorum:

module MyModule
  def self.method_a(param)
    @var ||= 0
    # other logic goes here
  end
end

Ben de onları başlatmak için başlatma yöntemi diyebiliriz:

def init
  @var = 0
end

ama bu böyle hatırlamak anlamına gelecektir.

Bunu yapmanın daha iyi bir yolu var mı?

CEVAP
30 Mart 2009, PAZARTESİ


Modül tanımında başlatılamadı.

module MyModule
  # self here is MyModule
  @species = "frog"
  @color = "red polka-dotted"
  @log = []

  def self.log(msg)
    # self here is still MyModule, so the instance variables are still available
    @log << msg
  end
  def self.show_log
    puts @log.map { |m| "A #@color #@species says #{m.inspect}" }
  end
end

MyModule.log "I like cheese."
MyModule.log "There's no mop!"
MyModule.show_log #=> A red polka-dotted frog says "I like cheese."
                  #   A red polka-dotted frog says "There's no mop!"

Bu örnek modül tanımlı değişkenleri ayarlar. Unutma, sen-ebilmek modülü daha sonra daha fazla örnek değişkenler ve Yöntem tanımları eklemek için yeniden alwasys, veya mevcut olanları yeniden tanımlamak için:

# continued from above...
module MyModule
  @verb = "shouts"
  def self.show_log
    puts @log.map { |m| "A #@color #@species #@verb #{m.inspect}" }
  end
end
MyModule.log "What's going on?"
MyModule.show_log #=> A red polka-dotted frog shouts "I like cheese."
                  #   A red polka-dotted frog shouts "There's no mop!"
                  #   A red polka-dotted frog shouts "What's going on?"

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • David Tedeyev

    David Tedeye

    20 AĞUSTOS 2011
  • eisleyhead

    eisleyhead

    11 Ocak 2006
  • happyjpy

    happyjpy

    22 AĞUSTOS 2009

İLGİLİ SORU / CEVAPLAR