简体   繁体   English

Ruby从块中返回的对象获取数组

[英]Ruby Get Array From Objects Returned in a Block

In Ruby, on certain occasions (ruby/gosu/texplay) I'v seen code like the following used: 在Ruby中,在某些情况下(ruby / gosu / texplay),我看到了类似以下代码的代码:

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

Would it be possible for me to write a similar function that can be used like so?: 我是否可以编写一个可以像这样使用的类似函数?

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

that would return and array: ["one", "two", "three"] 将返回并排列的数组:[“一个”,“两个”,“三个”]

ps this function isn't just for generating arrays and I am not wondering about methods to do so, all I need to know about is the syntax. ps该函数不仅用于生成数组,而且我不怀疑这样做的方法,我只需要了解语法。 Thanks in advance, ell. 预先感谢,ell。

TexPlay looks nice, how do you find it? TexPlay看起来不错,如何找到它? :) :)

I can't think of a way to do what you want, sorry. 对不起,我想不出一种方法来做你想要的。 But if you prefix every string with _ it is easy: 但是,如果为每个字符串加上_前缀,则很容易:

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

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

Where: 哪里:

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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM