簡體   English   中英

如何在鞋中使用課程?

[英]How to use classes in Shoes?

我是一個有點初學者的程序員,有使用Processing的背景。 我目前正在嘗試使用Shoes創建一個應用程序,但我對於對象和類如何工作感到困惑。

我知道以下內容將在Ruby中運行:

class Post
    def self.print_author
      puts "The author of all posts is Jimmy"
    end
end

Post.print_author

但為什么以下不會在鞋子中運行? 我怎么讓它運行?

class Post
    def self.print_author
      para "The author of all posts is Jimmy"
    end
end

Shoes.app do
    Post.print_author
end

我對Shoes並不太熟悉,但你可能遇到的問題是你試圖在Post類上調用一個名為para的方法,並且不存在這樣的方法。

當你調用Shoes.app do ... ,我懷疑Shoes正在將當前執行上下文更改為包含這些方法的上下文。 也就是說,你應該期望這個工作:

Shoes.app do
  para "The author of all posts is Jimmy"
end

這相當於:

Shoes.app do
  self.para("The author of all posts is Jimmy")
end

當你調用Post.print_authorself不再是Shoes對象,而是Post類。 那時你有幾個選擇:

  1. 傳入Shoes實例,並在其上調用特定於Shoes的方法。 當你不需要Post中的任何狀態時,你應該這樣做:

     class Post def self.print_author(shoes) shoes.para "The author of all posts is Jimmy" end end Shoes.app do Post.print_author(self) end 
  2. 創建一個接受Shoes對象的Post類,這樣您就不必繼續傳遞它。 如果Post有大量的狀態,你應該這樣做:

     class Post def initialize(shoes) @shoes = shoes end def print_author @shoes.para "The author of all posts is Jimmy" end end Shoes.app do post = Post.new(self) post.print_author end 
  3. 您可以在2.選項上使用變量來自動將調用傳遞給@shoes對象。 這開始進入Ruby元編程,我建議你避免,直到你對Ruby更加舒服,但我將它留在這里激起你的興趣:

     class Post def initialize(shoes) @shoes = shoes end def print_author para "The author of all posts is Jimmy" end def method_missing(method, *args, &block) @shoes.send(method, *args, &block) end end Shoes.app do post = Post.new(self) post.print_author end 

這樣做是告訴Ruby“如果在Post實例上找不到方法,請嘗試將其發送到@shoes實例”。 您可以想象,這可以允許一些非常好的DSL,但您必須小心使用它,因為如果您濫用它可能會使代碼難以遵循。

一種更簡單的方法是讓Post提供內容,然后在您的Shoes應用程序中,根據需要呈現該內容。 附帶好處:您可以在另一個打印到控制台的類中重用Post類。

class Post
  def self.print_author
    "The author of all posts is Jimmy"
  end
end

Shoes.app do
  para Post.print_author
end

class ConsoleApp
  def run
    puts Post.print_author
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM