Tag: lazy evaluation

Ruby挑战 – 方法链和懒惰评估

阅读文章http://jeffkreeftmeijer.com/2011/method-chaining-and-lazy-evaluation-in-ruby/后 ,我开始寻找方法链和懒惰评估的更好解决方案。 我想我已经用下面的五个规范封装了核心问题; 谁能让他们全部通过? 一切顺利:子类化,委托,元编程,但后者不鼓励。 将依赖关系保持在最低限度是有利的: require ‘rspec’ class Foo # Epic code here end describe Foo do it ‘should return an array corresponding to the reverse of the method chain’ do # Why the reverse? So that we’re forced to evaluate something Foo.bar.baz.should == [‘baz’, ‘bar’] Foo.baz.bar.should == [‘bar’, ‘baz’] end it ‘should be […]

当你的类没有定义#each时,返回Enumerator :: Lazy的最佳方法是什么?

可枚举#each依赖于你的枚举提供#each方法。 如果您的枚举没有#each方法,则无法使用#lazy 。 现在, Kernel#enum_for和#to_enum可以灵活地指定除#each之外的枚举方法: Kernel#enum_for(method = :each, *args) 但#enum_for和朋友总是构造普通(非懒惰)枚举器,而不是Enumerator::Lazy 。 我看到Ruby 1.9.3中的Enumerator提供了类似的#newforms: Enumerator#new(obj, method = :each, *args) 不幸的是,在Ruby 2.0中已经完全删除了构造函数。 此外,我认为它在Enumerator::Lazy上根本不可用。 所以在我看来,如果我有一个带有方法的类,我想返回一个惰性枚举器,如果该类没有#each那么我必须定义一些定义#each辅助类。 例如,我有一个Calendar类。 从一开始就提出列举每一个日期对我来说真的没有意义。 #each会没用。 相反,我提供了一个从开始日期(懒惰)枚举的方法: class Calendar … def each_from(first) if block_given? loop do yield first if include?(first) first += step end else EachFrom.new(self, first).lazy end end end 并且EachFrom类看起来像这样: class EachFrom include Enumerable def […]

如何创造无数可数的时代?

我希望能够让一个对象在Ruby中扩展Enumerable,成为一个无限的星期一列表(例如)。 所以它会产生:3月29日,4月5日,4月12日……等等 我怎样才能在Ruby中实现它?