使用map创建一个新数组

时间:2014-04-27 07:52:29

标签: ruby arrays iterator

我有以下数组

personality_types = ["bad", "good", "great"]

我想迭代通过personality_types并构造(也输出)这个数组:["bad person", "good person", "great person"]

我这样做了

personality_types = ["bad", "good", "great"]

personality_types.each do |x|
    x << ' person'

end

puts personality_type

但我希望能够使用.map函数来完成它。我如何使用.map来做到这一点?我无法弄明白。

这就是我所拥有的,但它不起作用(我只得到[“坏”,“好”,“好”]作为我的输出):

personality_types = ["bad", "good", "great"]

personality_types.map { |type| 
    type + " person" 
    }


puts personality_types

1 个答案:

答案 0 :(得分:2)

Array#map会返回 new 数组。您必须将其分配给变量:

personality_types = ["bad", "good", "great"]
personality_types = personality_types.map { |type| "#{type} person" }

或使用Array#map!直接更改数组:

personality_types = ["bad", "good", "great"]
personality_types.map! { |type| "#{type} person" }

personality_types
#=> ["bad person", "good person", "great person"]