0

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)

3 Answers 3

5

You can use Array#product, Enumerable#map and Array#join.

arr = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"]

["How 'ya doin, "].product(arr).map(&:join)
  #=> ["How 'ya doin, Edsger", "How 'ya doin, Ada", "How 'ya doin, Charles",
  #    "How 'ya doin, Alan", "How 'ya doin, Grace", "How 'ya doin, Linus",
  #    "How 'ya doin, Matz"] 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use map! if you want to modify the original array. But--however you approach it--an iterative method like each or map is your friend here because it implicitly handles the number of elements in the collection.

def badge_maker(array)
  array.map! do |el|
    "Hello " + el 
  end
end

array_one = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"]

badge_maker(array_one)

puts array_one
#=> Hello Edsger
#=> Hello Ada
#=> Hello Charles
#=> Hello Alan
#=> Hello Grace
#=> Hello Linus
#=> Hello Matz

Comments

1

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
   "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

1 Comment

Thanks, I've fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.