【问题标题】:Multiplying the contents of two arrays (not the arrays themselves)将两个数组的内容相乘(不是数组本身)
【发布时间】:2011-06-08 19:26:29
【问题描述】:

我想用套牌中的每张牌组成一个数组,所以它会是 ["Ac", "Ad", "Ah", "As", "Kc", ...] 虽然顺序并不重要.

难道没有一种方法可以使用注入来解决这个问题吗?这是我能做到的最接近的地方。

cards = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"] 
suits = ["c", "s", "d", "h"] 
ruby-1.9.2-p180 :025 > cards.inject(suits) { |suit, card| suit.map{|s| "#{card}#{s}"}}
 => ["23456789TJQKAc", "23456789TJQKAs", "23456789TJQKAd", "23456789TJQKAh"] 

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    这是你的目标吗?

    cards.map { |card|
      suits.map { |suit| "#{card}#{suit}" }
    }.flatten
    

    【讨论】:

    • 想使用注入,但这是我曾经拥有的解决方案。出于某种原因,每当我看到一个对我有意义的注入案例时,我最终都会使用 map。
    【解决方案2】:

    或者可能类似于

    cards.product( suits ).map(&:join)
    

    【讨论】:

      【解决方案3】:

      这不使用inject,但值得一提的是:Array#product。查看类似问题的答案here

      【讨论】:

        猜你喜欢
        • 2019-02-15
        • 1970-01-01
        • 2010-12-24
        • 2019-10-10
        • 2013-09-21
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多