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

标签 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

您可以在注释中看到代码要求的内容;将 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/

相关文章:

ruby - 在一条线上搜索和标记成对模式

JAVA:我需要按降序对数组中的一系列进行排序

javascript - 获取数组中每个项目的 id 并附加到选项值中的每个项目

arrays - Matlab:arrayfun,两个矩阵X,Y作为向量的分量

测试具有相同内容的 Go 中 map 的等价性,但测试失败

data-structures - 排序哈希表(map、dictionary)数据结构设计

ruby-on-rails - 避免对 rails 中的表进行多次查询

ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式

ruby-on-rails - 用于 CA Siteminder 身份验证的 Ruby 包装器(gem)

java - 如何根据条目集过滤 map 条目