组合数组中的元素(RubyMonk第6章第1课)

时间:2011-11-17 14:41:41

标签: ruby arrays map

我真的尝试过研究这个问题,但我现在已经接近它了,我担心如果不寻求帮助我就找不到解决方案。我正在浏览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

您可以在评论中看到代码要求的内容;获取英雄变量中的名称并将它们组合成一个名称。我已经尝试过测试一些看跌期权,除了“#”或“nil”之外我无法在STDOUT中得到任何东西,所以很明显我没有正确使用它。

目标的要求说使用.map或.collect但我认为你应该这样做,因为如果你不使用.map或.collect,它就会失败。< / p>

想法?

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

问题实际上要求您使用map方法。以下是供参考的链接:http://rubymonk.com/chapters/9-more-ruby/lessons/42-functional-programming-in-ruby

您可以在地图中调用Hero对象的full_name方法。但是您必须首先编写full_name方法的代码。提示说你可以使用Array#join。

希望现在很清楚!

答案 2 :(得分:1)

我解决了这个问题几乎与上面的帖子相同,但我的.map行看起来像这样:

heroes.map { |hero| hero.full_name }

这更符合问题的说明。

我必须说我有一段时间感到困惑,反馈是混乱的一部分(仍然是)。最初我使用.each方法并且反馈使我无法使用.map或.collect,所以我猜.each等于.map?

我终于使用了.map,反馈通过了我的代码注释:

  

不包含对'map'或'collect'的调用✔

我收到了代码,但没有收到评论。