1

在 Ruby 中,在某些情况下(ruby/gosu/texplay),我看到使用如下代码:

image.paint {
    circle 20, 20
    pixel 10, 10
}

我是否有可能编写一个可以像这样使用的类似函数?:

my_function {
    "one"
    "two"
    "three"
}

这将返回和数组:["one", "two", "three"]

ps 这个函数不只是用于生成数组,我并不想知道这样做的方法,我需要知道的只是语法。提前谢谢,嗯。

4

1 回答 1

3

TexPlay看起来不错,怎么找到的?:)

我想不出一种方法来做你想做的事,对不起。但是如果你在每个字符串前面加上_它就很容易:

function {
    _"one"
    _"two"
    _"three"
}

#=> ["one", "two", "three"]

在哪里:

def function(&block)
    Object.new.tap do |s| 
        s.instance_eval do            
            def _(var)
                @val ||= []
                @val << var
            end
        end
        s.instance_eval(&block)
     end.instance_variable_get(:@val)
end    
于 2010-10-04T23:11:20.567 回答