• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

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

ruby-on-rails 5次浏览

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

===========解决方案如下:

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

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 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)