2009-07-29 58 views
3

是否可以使用ruby在内联语句中定义块?事情是这样的:你可以用ruby定义一个块吗?

tasks.collect(&:title).to_block{|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}" } 

取而代之的是:

titles = tasks.collect(&:title) 
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}" 

如果说tasks.collect(&:title).slice(0, this.length-1)你怎么能“这个”是指传递给切片全阵列()?

基本上我只是在寻找一种方法将从一个语句返回的对象传递给另一个语句,而不一定会遍历它。

回答

4

你有点混淆,将返回值传递给方法/函数并在返回的值上调用方法。做你所描述的方法是这样的:

lambda {|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}"}.call(tasks.collect(&:title)) 

如果你想这样做,你正在尝试的方式,最接近的匹配是instance_eval,它可以让你的对象的上下文中运行的模块。所以那将是:

tasks.collect(&:title).instance_eval {"#{slice(0, length - 1).join(", ")} and #{last}"} 

但是,我不会这样做,因为它比替代选项更长和更不可读。

1

我不知道你想要做什么,但:

如果你说tasks.collect(&:标题).slice(0,this.length - 1)如何你让'this'引用传递给slice()的完整数组?

使用负数:

tasks.collect(&:title)[0..-2] 

此外,在:

"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}" 

你有什么奇怪你报价的时候,我想。

+0

谢谢,好了解的负数。 – bwizzy 2009-07-29 15:17:29

1

我真的不明白,为什么你会想,但你可能会增加,需要一个块中的Ruby类的功能,并将自身作为一个参数...

class Object 
    def to_block 
    yield self 
    end 
end 

此时你将能够拨打:

tasks.collect(&:title).to_block{|it| it.slice(0, it.length-1)} 

当然,修改对象类不应该掉以轻心当与其他图书馆合并有可能引起严重的后果。

+0

有没有办法做到这一点,产生自我内联? – bwizzy 2009-07-29 15:18:09

0

虽然这里有很多很好的答案,也许你在一个客观的角度来看待的东西多是这样的:

class Array 
    def andjoin(separator = ', ', word = ' and ') 
    case (length) 
    when 0 
     '' 
    when 1 
     last.to_s 
    when 2 
     join(word) 
    else 
     slice(0, length - 1).join(separator) + word + last.to_s 
    end 
    end 
end 

puts %w[ think feel enjoy ].andjoin # => "think, feel and enjoy" 
puts %w[ mitchell webb ].andjoin # => "mitchell and webb" 
puts %w[ yes ].andjoin # => "yes" 

puts %w[ happy fun monkeypatch ].andjoin(', ', ', and ') # => "happy, fun, and monkeypatch" 
相关问题