Ruby: block 和产量

标签 ruby class yield block

我遇到了这个关于使用 blocks e 然后用 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"]

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

最佳答案

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

关于Ruby: block 和产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682710/

相关文章:

ruby-on-rails - 无法为数据库添加种子;由于连接被拒绝而无法工作?

c++ - 使用工厂模式按名称实例化类

c# - Yield Break 是否返回一个值?

objective-c - 如何使用 objective-c 实现 go 样式 channel (CSP)?

javascript - ES6 yield (yield 1)(yield 2)(yield 3)()

ruby-on-rails - Rails-闪存[:alerts] not showing

ruby-on-rails - #<String :0x00000003a27a58> 的未定义方法 `each'

ruby - 在发布 gem 之前编译 Assets

html - 一个CSS类可以包含另外两个类吗

具有 asio get 方法成员的 C++ 对象