在Ruby中将输出存储到数组中

时间:2016-08-01 23:44:35

标签: ruby-on-rails ruby rspec

所以我需要创建一个接受名称数组并输出一组字符串的方法。如何将输出存储到数组中?所以我没有一个名字数组,而是有一系列问候语?



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)
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

您可以使用Array#productEnumerable#mapArray#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"] 

答案 1 :(得分:2)

如果要修改原始数组,可以使用map!。但是 - 无论你接近它 - 像eachmap这样的迭代方法都是你的朋友,因为它隐含地处理了集合中元素的数量。

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

答案 2 :(得分:1)

这是未经测试的,但应该这样做:

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)

或者,如果您想要实际转换原始数组,而不是创建新的问候数组,那么请执行以下操作:

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