Steven Aguilar Steven Aguilar - 4 months ago 30
Ruby Question

Stored output into an array in Ruby

So I need to create a method that takes in an array of names and outputs a set of strings. How do I stored that output into an array? so instead of having an array of names I have an array of greetings?



def badge_maker(array)
array.each do |i|
counter = 0
while counter < 7
array[counter] << "Hello, my name is #{i}."
counter += i
end
return array
end
end
arrayOne = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"]

badge_maker(arrayOne)




Answer

This is untested, but should do the trick:

def badge_maker(names)
  greetings = [] # initialize greetings as an empty array
  names.each do |name| # for each name in the names array
    greetings << "Hello, my name is #{name}." # add a greeting for that name
  end
  return greetings # return the array of all greetings, at the end
end
arrayOne = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"]

badge_maker(arrayOne)

Or, if you're wanting to actually transform the original array, rather than create a new array of greetings, then do this:

def badge_maker(names)
  names.map do |name| # for each name in the names array
    return "Hello, my name is #{name}." # convert it to a greeting for that name
  end
end
arrayOne = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"]

badge_maker(arrayOne)
# now, arrayOne will contain an array of greetings, not names