我遇到了这个关于使用 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/