我真的尝试过研究这个问题,但我现在离它太近了,我担心如果不寻求帮助我就找不到解决方案。我正在学习 RubyMonk,其中一个练习让我完全不知所措。
class Hero
def initialize(*names)
@names = names
end
def full_name
# a hero class allows us to easily combine an arbitrary number of names
end
end
def names
heroes = [Hero.new("Christopher", "Alexander"),
Hero.new("John", "McCarthy"),
Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
# map over heroes using your new powers!
end
您可以在注释中看到代码要求的内容;将 heroes 变量中的名字组合成一个名字。我已经尝试测试一些 put,除了“#”或“nil”之外无法在 STDOUT 中获取任何内容,很明显我没有正确使用它。
目标的要求说不使用 .map 或 .collect 但我认为你实际上应该这样做,因为如果你不使用 .map 或 .collect 则它不符合要求。
想法?
最佳答案
class Hero
def initialize(*names)
@names = names
end
def full_name
@names.join(' ')
end
end
def names
heroes = [Hero.new("Christopher", "Alexander"),
Hero.new("John", "McCarthy"),
Hero.new("Emperor", "Joshua", "Abraham", "Norton")]
heroes.map(&:full_name)
end
关于ruby - 组合数组中的元素(RubyMonk 第 6 章第 1 课),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168972/