سؤال

I have the following array

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

I want to iterate through personality_types and construct(also output it) this array: ["bad person", "good person", "great person"]

I have done it this way

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

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

end

puts personality_type

but I want to be able to do it using the .map function instead. How can I use .map to do this? I haven't been able to figure it out.

This is what I have, but it's not working(I only get ["bad", "good", "great"] as my output):

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

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


puts personality_types
هل كانت مفيدة؟

المحلول

Array#map returns a new array. You have to assign it to the variable:

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

Or use Array#map! to directly change the array:

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

personality_types
#=> ["bad person", "good person", "great person"]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top