加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 笛卡尔积ruby

发布时间:2020-12-16 21:17:26 所属栏目:百科 来源:网络整理
导读:class CartesianProductinclude Enumerable# your code hereend#Examples of usec = CartesianProduct.new([:a,:b],[4,5])c.each { |elt| puts elt.inspect }# [:a,4]# [:a,5]# [:b,4]# [:b,5]c = CartesianProduct.new([:a,[])c.each { |elt| puts elt.insp
class CartesianProduct
include Enumerable
# your code here
end
#Examples of use
c = CartesianProduct.new([:a,:b],[4,5])
c.each { |elt| puts elt.inspect }
# [:a,4]
# [:a,5]
# [:b,4]
# [:b,5]
c = CartesianProduct.new([:a,[])
c.each { |elt| puts elt.inspect }
# (nothing printed since Cartesian product
# of anything with an empty collection is empty)

我是ruby的新手.我理解如何定义笛卡儿积的实例方法,但我对此毫无头绪.我应该如何构造类对象以满足要求.

解决方法

我不会使用一个类,但保持问题的结构,我写道:
class CartesianProduct
  include Enumerable

  def initialize(xs,ys)
    @xs = xs
    @ys = ys
  end

  def each
    return to_enum unless block_given?
    @xs.each do |x| 
      @ys.each { |y| yield [x,y] }
    end
  end
end

相反,如果懒惰很重要,我只需编写xs.product(ys)或构建我自己的Array#lazy_product(参见本ticket).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读