在数组中添加长度或每个字符串并创建一个附加结果的新数组

时间:2015-07-12 14:30:11

标签: arrays ruby

我需要做以下事情:

  

编写一个带有String的函数,并返回一个数组/列表,其中每个单词的长度都添加到每个元素

示例:

add_length('apple ban') => ["apple 5", "ban 3"]  
add_length('you will win') => ["you 3", "will 4", "win 3"]

我可以找到每个单词的长度,但我的问题是,如何创建一个新的数组,将长度附加到每个单独的元素?我想我需要再次使用地图,但我不确定如何......

这就是我计算出的长度:

def add_length(str)  
   str.split(" ").map(&:length).to_s
end

3 个答案:

答案 0 :(得分:3)

稍作修改可以使其有效:

'apple ban'.split(" ").map {|w| w + ' ' + w.length.to_s}
# => ["apple 5", "ban 3"]

答案 1 :(得分:2)

您可以使用字符串插值来避免字符串连接和to_s调用。此外,当您使用(" ")在空格中拆分字符串时,不需要split参数:

def add_length(words)
  words.split.map { |word| "#{word} #{word.length}" }
end

答案 2 :(得分:1)

使用collect方法

def add_length(str)

   str.split(" ").collect { |e| e + ' ' + e.length.to_s }

end

p add_length('apple ban')

输出:

["apple 5", "ban 3"]