【问题标题】:Ruby: blocks and yieldRuby:块和产量
【发布时间】:2012-03-29 18:37:09
【问题描述】:

我遇到了这个关于使用 blocks 然后用 yield 调用它们的练习。它看起来像这样:

class Hero
  def initialize(*names)
    @names = names
  end
  def full_name
    # a hero class allows us to easily combine an arbitrary number of names
    # this is where yield should be
  end
end

def names
  heroes = [Hero.new("Christopher", "Alexander"),
            Hero.new("John", "McCarthy"),
            Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
  # I have to use #map and #join to unify names of a single hero
end

返回值应该是这样的:

["Christopher Alexander", "John McCarthy", "Emperor Joshua Abraham Norton"]

我知道如何使用块和产量。在此之前我做了非常简单的练习,但我无法解决这个问题。

【问题讨论】:

    标签: ruby class yield block


    【解决方案1】:

    使用Array#join。你不需要yield 或任何花哨的东西。

    【讨论】:

    • 英雄中的每个元素都是一个对象。它不是一个数组,所以我不能使用 join: undefined method `join' for #
    • Array#join 是编写类Array 的“实例方法join”的约定。
    • 对不起,我是红宝石的新手。 Join 是 Array 类的一种方法。但是英雄是由英雄类的实例组成的,我不知道如何加入它们,因为它们不是数组。
    • 正如请求所述,这是一个关于块和产量的练习。没有意义,但他必须根据练习的要求提供解决方案。
    【解决方案2】:

    这似乎是一个奇怪的请求,但如果您必须在 cmets 中编写时使用 yield 和 join,这就是解决方案:

    class Hero
      def initialize(*names)
        @names = names
      end
      def full_name
        if block_given?
          yield @names
        else
          @names.join(' ')
        end
      end
    end
    
    def names
      heroes = [Hero.new("Christopher", "Alexander"),
                Hero.new("John", "McCarthy"),
                Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
      heroes.map { |h| h.full_name { |name| name.join(' ') } }
    end
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 2011-03-05
      • 2014-08-01
      • 2015-03-01
      • 2019-02-16
      • 2016-06-08
      • 2010-12-08
      • 2020-06-18
      • 2017-02-13
      相关资源
      最近更新 更多