我有以下数组
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
答案 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"]