[英]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_author
, self
不再是Shoes对象,而是Post类。 那时你有几个选择:
传入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
创建一个接受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
您可以在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.