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

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

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)

回答:

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

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

回答:

你c如果您想修改原始数组,请使用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

回答:

您可以使用Array#product,Enumerable#map和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"]

以上是 将输出存储到Ruby中的数组中 的全部内容, 来源链接: utcz.com/qa/259945.html

回到顶部